Question

I am trying to change the image on mousedown and revert back to the initial image on mouseup. The image is changing on mousedown but it is not reverting to the initial image on mouseup. The alert in the mouseup function doesnt appear... What is going wrong?

$(#mydivid).bind('mousedown', function() {
        document.getElementById(mydivid).style.backgroundImage = "url(Images/new.png)";
        alert("mousedown");
    });



    $(#mydivid).bind('mouseup', function() {
        document.getElementById(mydivid).style.backgroundImage = "url(Images/initial.png)";
alert("mouseup");
    });

I have observed that when I bind more than 1 event to the same div, the first eventhandler works and the others are ignored...How do i ensure that all events are handled?

Was it helpful?

Solution

You should get rid of the alerts. That's causing the problem.

Another thing i noticed is that '#mydivid' isn't encapsulated in quotes.

Also, if you're using jquery 1.7+, then it is recommended to use 'on' instead of 'bind'.

As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document. For earlier versions, the .bind() method is used for attaching an event handler directly to elements.

Source: http://api.jquery.com/bind/

JQuery also has a method to change the CSS properties of an element. Maybe you could consider that too for changing the background.

http://api.jquery.com/css/


But, like i said, remove the alerts and it should work just fine. See this example:

http://jsfiddle.net/fS9Ct/1/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top