Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using the same function of different events

This seems pretty simple, but I can't figure it out. I'm new to javascript/ jquery.

i want to trigger a function to move a div onmouseover, and another onmouseout. I want to call this same function on several different divs. how would I do this without writing multiple functions?

  <div id="indexJoinBanner" onmouseover="moveDivRight()" onmouseout="moveDivLeft()"> 
  <!-- end #indexJoinBanner --></div>
  <div id="indexJoinBanner2" onmouseover="moveDivRight()" onmouseout="moveDivLeft()"> 
  <!-- end #indexJoinBanner2 --></div>



function moveDivRight(){
  $("#indexJoinBanner").animate({
    left: "0px",
  },500 );
};

function moveDivLeft() {
  $("#indexJoinBanner").animate({
    left: "-150px",
  },500 );
}

Thanks

like image 307
vinylDeveloper Avatar asked Feb 15 '26 07:02

vinylDeveloper


1 Answers

$("#indexJoinBanner, #indexJoinBanner2").hover(function () {
    $(this).animate({left: '0px'}, 500);
},
function () {
    $(this).animate({left: '-150px'}, 500);
});

.hover allows you to bind mouseover and mouseout simultaneously, but you can also bind them separately.

You can use this to refer to the object that is the target of the binding (even if you bind to multiple elements at once).

You can also bind named functions if you want to.

NOTE: in this solution, the onmouseover, etc. attributes are not required in the HTML at all.

like image 117
Explosion Pills Avatar answered Feb 17 '26 19:02

Explosion Pills



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!