Question

The HTML:

<a id="the_link" class="folded" href="#">Click me</a>
<div id="content">This is some content to be toggled.</div>

Two functions that each show or hide the content:

function shower() {
  $("body").on("click", "#the_link.folded", function(event) {
    $("#content").show();
    $("#the_link").html("Hde info").removeClass("folded").addClass("unfolded");
  });
}

function hider() {
  $("body").on("click", "#the_link.unfolded", function(event) {
    $("#content").hide();
    $("#the_link").html("See more info").removeClass("unfolded").addClass("folded");
  });
}

If I use jQuery, the code works:

$(document).ready(function() {  
  shower();
  hider();
})

If I use Zepto, the code does not work:

Zepto(function($){  
  shower();
  hider();
})

Why?

Was it helpful?

Solution

totally odd , i didnt really use zepto before . But you're right there is something wrong in the library it self (or thats just the way they operate).

the problem is that binding the even if the element doesnt already exist wont work .

And that if you change the element's class on the fly the same event will be still bound to it even though the class has changed . so you have to use off to unbind the event then rebind it in the other function and vise versa . jsfiddle

function shower() {
  $("body").on("click", "#the_link.folded", function(event) {
      console.log('shower function');
    $("#content").show();
    $("#the_link").removeClass("folded").addClass("unfolded").html("Hde info");
       $("body").off("click", "#the_link.folded");
      hider();
  });
}

function hider() {

  $("body").on("click", "#the_link.unfolded",function(event) {
      console.log('hider function');
    $("#content").hide();
    $("#the_link").removeClass("unfolded").addClass("folded").html("See more info");
      $("body").off("click", "#the_link.unfolded");
      shower();
  });
}


  shower();
  hider();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top