Why are the calls doubling each time?

Shown here: JS Fiddle

This is the code we're concerned with:

    doit1();

    function doit2(){
        $("#evtTarget").on("click", function(evt) {
            $("#evtTarget").addClass("highlighted");
            $("#evtTarget").on("mouseover mouseleave", highlight);
            $("#evtTarget").html("<p>You Turned on the hover effect!</p>");
            doit1();
        });}

    function doit1(){
        $("#evtTarget").on("click", function(evt) {
            $("#evtTarget").off("mouseover mouseleave", highlight);
            $("#evtTarget").html("<p>You shut off the hover effect!</p>");
            $("#evtTarget").removeClass("highlighted");
            console.log("check");
            doit2();
        });}

Something about this code, which I can't figure out, calls back and forth and doubles the call each time. This eventually breaks the page. Why is this and how do I do it better?

Answers


On both functions, change $("#evtTarget").on("click", function(evt) { To $("#evtTarget").off( "click" ).on("click", function(evt) {


Your code is sort of "reentrant"... You only need to set your onClick once...

Try:

$(function() {
  turnItOn();

  $("#evtTarget").on("click", function(evt) {
    if ($("#evtTarget").hasClass("highlighted")) {
      turnItOff();
    } else {
      turnItOn();
    }
  });
});
function turnItOn() {
  $("#evtTarget").addClass("highlighted");
  $("#evtTarget").on("mouseover mouseleave", highlight);
  $("#evtTarget").html("<p>You Turned on the hover effect!</p>");
}

function turnItOff() {
  $("#evtTarget").off("mouseover mouseleave", highlight);
  $("#evtTarget").html("<p>You shut off the hover effect!</p>");
  $("#evtTarget").removeClass("highlighted");
}

function highlight(evt) {
  $("#evtTarget").toggleClass("highlighted");
}

As seen in this version of you fiddle:

https://jsfiddle.net/pnz9eooz

Or turn the events off, like Alon suggested while I was writing this :)


Need Your Help

Copying only non-existent files in ant

java ant copy java-web-start

I'm deploying my project to a web-server to be deployed with java Web Start. However, Web Start uses modification date to figure out whether to download the resources again (by default).