javascriptjqueryhtmlonmouseoveronmouseclick

Change onmouseover="this.src='xxx'" when item is clicked


I have this image which on hover changes the src:

<img id="apripreventivo" src="img.svg" onmouseover="this.src='img_hover.svg'" onmouseout="this.src='img.svg'">

Then I have a script that when that image is clicked toggles a div (#contact-form):

$(document).ready(function(){

        $("#contact-form").hide();
        $("#apripreventivo").show();

    $('#apripreventivo').click(function(){
    $("#contact-form").slideToggle();
    });

});

How can I rewrite the above function to also have that when the image (#apripreventivo) is clicked, its onmouseover src changes to e.g. *img_hover2.svg* ("normal" src and onmouseout be the same. And still #contact-form" div toggling on click). Then when clicked again the onmouseover should return to original (*img_hover.svg*).


Solution

  • I've gotten you most of the way: JSFiddle.

    The trick is simply to change the attribute of the img tag using jQuery's $.attr() method.

    $('img').click(function() {
        $(this).attr("onmouseover", "this.src='http://newevolutiondesigns.com/images/freebies/cat-wallpaper-7.jpg'");
    })
    

    You can easily write a function which checks the current value of this attribute, then sets the correct value on click. Hope this helps!