简体   繁体   中英

Switch what triggers an event in jQuery without reloading?

So I have a website which loads gifs that are paused at the start. I have .on("event") functions that work fine separately, on click and on hover. However I would like to let the user choose which of these methods they would like to use to play the gif with a setting. The code I am working with is something like:

if (hoverOn) {
    $(document).on("hover", ".content", function () {
        playTheGif();
    }
}
else {
   $(document).on("click", ".content", function () {
       playTheGif();

and of course, when on click it pauses the gif if it's already playing.

I have buttons to set the bool hoverOn, and that works to change the bool but it doesn't reload the page so the trigger to play the gif stays the same, even if the bool is changing. Is there any way to make that if/else search dynamic in the page?

Thanks, I hope I explained myself enough.

Switch the position of the boolean test and the handlers so that the boolean is tested inside of the handlers:

$(document).on("hover", ".content", function () {
  if (hoverOn) playTheGif();
})
$(document).on("click", ".content", function () {
  if (!hoverOn) playTheGif();
});

I would probably try to combine them.

$(document).on("click mouseenter", ".content", function (e) {
    //do nothing for hoveron,click or hoveroff,hover
    if (hoverOn ^ e.type === "mouseenter") return;

    playTheGif();
});

 var hoverOn = true; $(document.body).on("click mouseenter", ".content", function (e) { //do nothing for hoveron,click or hoveroff,hover if (hoverOn ^ e.type === "mouseenter") return; //playTheGif(); $(e.target).css('backgroundColor', 'green'); }); $('button').on('click', function(){ hoverOn = !hoverOn; $('#interaction').text(hoverOn ? 'hover' : 'click' ); $('.content').css('backgroundColor', ''); }); 
 .content { display: inline-block; width: 150px; height: 150px; background-color: red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="content"></div> <div class="content"></div> <div class="content"></div> <div class="content"></div> <div> <button>Toggle Interaction</button> <span id="interaction">hover</span> </div> 

You can unset the current events and set the new one when the user is toggling hoverOn. For example:

if (hoverOn) {
    $(".content").unbind("click");
    $(document).on("hover", ".content", function () {
        playTheGif();
    }
}
else {
    $(".content").unbind("hover");
    $(document).on("click", ".content", function () {
        playTheGif();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM