Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle Click Alternative

If you go and view the api of JQuery's .toggle you can see it's been deprecated since 1.8 and removed in 1.9.

This is what I would normally use if I was using an older version of JQuery. [Example]

$('.drop-section a').toggle(function() {
  $(this).css({"color" : "#666", "background-color" : "#1f1f21"});
},
function() {
  $(this).css({"color" : "#a9a9a9", "background-color" : "#444"});
});

I'm trying to do a simple workaround from a click event. but I'm having trouble getting it to work. [Here's the fiddle]

I know I can use toggleClass, but I want to accomplish this effect using something like below.

$('.drop-section a').click(function() {
  var clicked = false;

  if (clicked) {
    clicked = false;
    $(this).css({"color" : "#a9a9a9", "background-color" : "#444"});
  }
  clicked = true;
  $(this).css({"color" : "#666", "background-color" : "#1f1f21"});

});

Any help is greatly appreciated.

like image 401
Michael Schwartz Avatar asked Sep 23 '26 05:09

Michael Schwartz


1 Answers

In your case, I would just use toggleClass(), which is still supported. Add a class that changes the button to the "on" state, and then toggle that class on and off on click. I altered your JSbin to demonstrate: New JSBin

Edit: If you're determined to do it with your code, or have other requirements you're not telling us about: your clicked variable is destroyed once you leave the handler, so it doesn't "remember" when it's been clicked. You also don't want to just make it global, because then it wouldn't work with multiple buttons.

What you want is to attach the "clicked" data to the element that you're toggling things on, which is easy with the data() method:

$('.drop-section a').click(function() {
  if ($(this).data('clicked')) {
    $(this).data('clicked',false);
    $(this).css({"color" : "#a9a9a9", "background-color" : "#444"});
  } else {
    $(this).data('clicked',true);
    $(this).css({"color" : "#666", "background-color" : "#1f1f21"});      
  }
});

Also, I'm not sure why the second bit isn't wrapped in an else{}, but it should be, otherwise it will just always end up "clicked", regardless of state. I (accidentally, versioning in JSBin is lacking compared to jsfiddle) updated the above link to use this code. Old link here. Make sure to click the "Run with JS" button if it doesn't seem to be working.

like image 142
cincodenada Avatar answered Sep 24 '26 20:09

cincodenada