Jump to content

jQuery if else statement shorthand for .attr()


Junitar
 Share

Recommended Posts

Hi,

I'm training myself at jQuery doing some exercices. I've written the following code:

<button id="btn" title="menu">menu</button>
jQuery(function($){  
  $("#btn").click(function(){
  	
    var btn = $(this);
    var currentText = btn.text();
    // alert(currentText);

    if (currentText == "menu") {
      btn.text("close");
      btn.attr("title","close menu");
    }
    else {
      btn.text("menu");
      btn.attr("title","menu");
    }
  });
});

and I would like to simplify it as much as possible, using if else statement shorthand.

I've managed to get it works for the .text() method

btn.text(currentText == "menu" ? "close" : "menu"); 

but not for the .attr().

I've tried btn.attr("title", "menu" == "menu" ? "close" : "menu"); and btn.attr("title", btn.attr("title") == "menu" ? "close" : "menu"); among many other things but I can't figure out how to make it works.

 

 

Any help?

Edited by Junitar
Link to comment
Share on other sites

"menu" == "menu" is a tautology, so it would never return the false value.

 

This should work.

btn.attr("title", currentText == "menu" ? "close menu" : "menu");

I recommend being very familiar with Javascript before learning jQuery.

Link to comment
Share on other sites

Thanks for the help, I've already tried

btn.attr("title", currentText == "menu" ? "close menu" : "menu");

but it didn't work properly (the title changed to "close menu" when it should be "menu" and vice versa).

 

Anyway, I've just found what I was doing wrong…

btn.attr("title", btn.attr("title") == "menu" ? "close" : "menu"); 

is now working fine but I formerly called my button title "Menu" with a capitalized "m", while I used a small "m" in the btn.attr() which screwed it all.

Edited by Junitar
Link to comment
Share on other sites

I've just tested again your suggestion and it works indeed. Don't know exactly what I previously did. I guess my brain just needs some rest right now, I've done too many exercices today, it's a big mess in my mind :happy0046:

Edited by Junitar
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...