Jquery Toggle Id's Instead Of Classes?
Solution 1:
You really should use classes for that. IDs are unique within a page and should be used as points where you catch events ( via $.live()
or some other method which uses event delegation ). Besides , if you think of using IDs because they have higher specificity in CSS rules , then you are going the wrong way.
In short: bad idea, stick to toggling classes.
Solution 2:
EDIT:
After reading OP's comment - I believe this is what he is looking for a way to highlight an "active" link on click. And Yes, teresko is definitely right that you should be toggling the classes, not the ID's.
This is the essence of a jQuery snippet that you may be looking for:
$("li").bind('click', function(){
// remove the active class if it's thereif($("li.active").length) $("li.active").removeClass('active');
// add teh active class to the clicked element
$(this).addClass('active');
});
Check out the jQuery toggle api.
It's a little confusing because a simple google search on jQuery toggle brings you to the show/hide toggle documentation. But, .toggle()
can be used to alternate functions - you can even add more than two.
like so...
$("el").toggle(
function(){
$(this).css('background-color', 'red');
},
function(){
$(this).css('background-color, ''); // sets the bg-color to nothing
});
Solution 3:
jQuery doesnt has toggleId() function . But you can create your own id toggle function .
functiontoggleId(className,id)
{
var tag = document.querySelector('.'+className);
tag.id = tag.getAttribute("id") ? '' : id;
}
toggleId("myClass","id");
this will toggle id ( id and NULL ) of myClass element .
another example for toggling between two id
suppose you want to toggle between two id ( id1 and id2 ) of an element then
functiontoggleId(className,id1,id2)
{
var tag = document.querySelector('.'+className);
tag.id = tag.getAttribute("id") ? id2 : id1;
}
toggleId("myClass","id1","id2");
Post a Comment for "Jquery Toggle Id's Instead Of Classes?"