Slide or drag any jQuery/bootstrap slider programatically

This article provides a hack to slide or drag any kind of slider or dragabble element (which is dependent on jQuery) programatically. This code snippet is going to be a normal jQuery code which will manipulate the position of the element itself.

Code snippet:

	var targetElement = $('#myElement'); //use your own selector to select the element
	var mouseMoveEvent = $.Event('mousemove');
	mouseMoveEvent.pageX = 0; //put your own logic to set the value
	mouseMoveEvent.pageY = 0; //put your own logic to set the value

	$(targetElement).trigger('mousedown');
	$('body').trigger(mouseMoveEvent);
	$(targetElement).trigger('mouseup');

Explaining the code

Firstly, we are creating a mousemove event explicitly. The event need to have two parameters. pageX and pageY, both represent the new X and Y coordinate of your element. I’m setting both the values to zero. You need to put your own logic to determine a value and then set it to pageX and pageY. Remember they are going to be the position with respect to the window and not the element.

After that I’m triggering a mousedown event; followed by my created mousemove and finally ending up with mouseup. This is similar to clicking on the element, dragging and leaving the mouse left button.

 

About This Author

Hello! I am Paul Shan, a JavaScript Expert, Full Stack and DevOps Engineer cum Consultant based out of Bengaluru, India.