jquery list item class toggle - javascript

I have a simple function to toggle list item class from "active" to "inactive". What is the most efficient way (i.e., using the least amount of code) to set all other list items to "inactive" so that there can only be one "active" list item? Please see below for an example. Thank you
<ul class="menu">
<li id="one" class="active">One</li>
<li id="two" class="inactive">Two</li>
<li id="three" class="inactive">Three</li>
<li id="four" class="inactive">Four</li>
<li id="five" class="inactive">Five</li>
</ul>
<script>
$('#one').click(function () {
if ($(this).hasClass("inactive")) {
$(this).removeClass("inactive").addClass("active");
} else {
$(this).removeClass("active").addClass("inactive");
}
});
</script>

This can work:
$('.menu li').click(function () {
$('.menu li').not(this).removeClass('active').addClass('inactive');
$(this).addClass('active').removeClass('inactive');
});
or
$('.menu li').click(function () {
$('.menu li').removeClass('active').addClass('inactive');
$(this).toggleClass('active inactive');
});
The second method is shorter, but slower.
http://jsperf.com/toggle-vs-add-remove
Edit: This one is shorter and faster:
$('.menu li').click(function () {
$('.menu li').not(this).removeClass('active');
$(this).addClass('active');
});
If performance is really a problem you can store your menu in a variable and perform operations on this variable, like:
var $menu = $('.menu li');
$menu.click(function () {
$menu.not(this).removeClass('active');
$(this).addClass('active');
});

For brevity:
$('ul.menu li').click(function () {
$(this).siblings().attr('class', 'inactive').end().toggleClass('inactive active');
});
JS Fiddle demo (127 characters, whitespace-removed character-count: 115).
Character-counts at JS Fiddle, since brevity was the intent, it seems.
Unfortunately, given the problem identified in the comments, below, a corrected implementation is somewhat more verbose than the (currently-accepted answer), alternatives being:
$('ul.menu li').click(function () {
var t = this;
$(this).siblings().add(t).attr('class', function (){
return t === this ? 'active' : 'inactive';
});
});
JS Fiddle demo (174 characters, whitespace-removed character-count: 133).
Or:
$('ul.menu li').click(function () {
var t = this;
$(this).parent().children().attr('class', function (){
return t === this ? 'active' : 'inactive';
});
});
JS Fiddle demo (176 characters, whitespace-removed character-count: 135).
Of course, white space-removed jQuery does become somewhat unreadable, but still: I claim the, uh, moral victory...
References:
add().
attr().
children().
end().
siblings().
toggleClass().

$('ul li').click(function() {
$('ul li').each(function() {
$(this).removeClass('active');
});
$(this).addClass('active');
});
JSFiddle

If SEO is not important and to use the less amount of code I would say use a radio-button list.
Then you can style and interact in JavaScript by using the ":checked" selector.

If you're already using jQuery UI, you can take advantage of the selectable function. That would get you what you want with the least amount of code.
http://jqueryui.com/selectable/

Related

JQuery and onclick doesn't work in this context

striving to make jquery and li working in this context:
<div id="statLateralMenu">
<h3>Statistics</h3>
<ul>
<li id="id1" class="selected">Stat 1</li>
<li id="id2">Stat 2</li>
</ul>
</div>
s
$(function() {
$("#statLateralMenu li").click(function()
{
alert( "A" );
$("#statLateralMenu li").removeClass("selected");
$(this).addClass("selected");
});
}
);
I am pretty sure the error is very stupid also because I've already implemented this code in another area of my page and it works perfectly, but this time really I can't make it working.
Any clue please?
EDIT:
I am not able even to fire the alert, my problem is not (yet) to change the class's li.
JQuery is loaded as in the same page I have another ul/li complex and it works perfectly
EDIT 2:
At this point maybe I am messing up a bit, but using my code here it doesn't work as well: https://jsfiddle.net/nakjyyaj/4/
It seems to work :
$(function() {
$("li").click(function() {
$("li").removeClass("selected");
$(this).addClass("selected");
});
});
.selected{background:yellow}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>azerty</li>
<li>bzerty</li>
<li>czerty</li>
</ul>
To deal with dynamic content you can use event delegation :
$(function() {
$("ul").on("click", "li", function() {
$("li").removeClass("selected");
$(this).addClass("selected");
});
});
setTimeout(function () {
$("p").remove();
$("ul").html(""
+ "<li>azerty</li>"
+ "<li>bzerty</li>"
+ "<li>czerty</li>"
);
}, 1000);
.selected{background:yellow}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Wait 1 second.</p>
<ul></ul>
Further reading : https://stackoverflow.com/a/46251110/1636522.
try to change
$("#statLateralMenu li").removeClass("selected"); to
$(this).removeClass("selected");
like that
$(function() {
$("#statLateralMenu li").click(function()
{
alert( "A" );
$(this).removeClass("selected");
$(this).addClass("selected");
});
}
);
but if you want only to change design elements you can use :hover
li:hover {
background-color: yellow;
}
In your JSFiddle, you forgot to load JQuery framework.
You don't need script tag in JSFiddle (no need and ).

Check if element is hovered over in jQuery

How can one check if the cursor is hovered over in jquery or js.
I have tried $('#id').is(':hover') but this doesnt seem to be working at all.
I have to mention that i am calling this line inside of a hover() function could this maybe be the problem?
here is my code:
$(document).ready(function() {
/* On hover function, over the menu items */
$('nav ul li').hover(function(){
$('nav ul li').css("background-color", "");
$('#append').css("background-color", "");
$(this).css("background-color", "#9999FF");
$('#append').css("background-color", "#9999FF");
var append;
if($('#menu-item-12')) {
append = 'news';
}else if($('#menu-item-9:hover')) {
append = 'account';
}else if($('#menu-item-11').is(':hover')) {
append = 'check out';
}
$('#appendp').empty();
$('#appendp').append(document.createTextNode(append));
});
Hope someone can tell me whats wrong.
here is jsfiddle link, i did my best :) https://jsfiddle.net/xsv325ef/
A nice way to do it is to store the related texts into an Object literal,
and recall the text depending on the hovered element ID:
fiddle demo
$(function() { // DOM ready shorthand ;)
var $appendEl = $('#appendp');
var id2text = {
"menu-item-12" : "unlock this crap",
"menu-item-9" : "check your gdmn account",
"menu-item-11" : "check the hell out"
};
$('nav ul li').hover(function(){
$appendEl.text( id2text[this.id] );
});
});
Regarding the colors... use CSS :hover
You just need to check if hovered item has this id.
Something like this: https://jsfiddle.net/hrskgxz5/5/
if(this.id === 'menu-item-11') {
append = 'check out';
alert('hovered');
}
$('li').hover(function(){
$(this).css("background-color", "#9999FF");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<ol>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>
<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
You should notice that jQuery .hover() function takes 2 handler function, and here you only provide one. Check the official documentation here.
In your case, you may just use .mouseover() to add a class on top of it, and then set your styles in css file. (Document here)
For example:
$(document.ready(function(){
$('nav ul li').mouseover(function() {
$(this).addClass('active');
});
});
If you do need to toggle the class for that element, the hover function should be as follow:
$(document.ready(function(){
$('nav ul li').hover(function() {
// Stuff to do when the mouse enters the element
$(this).addClass('active');
// Other styles you want to do here
// ...
}, function() {
// Stuff to do when the mouse leaves the element
$(this).removeClass('active');
// Other styles you want to remove here
// ...
});
});
Edit:
As I found out, jQuery .hover() function DO accept single handler. In that case, you'll have to let the class toggle inside:
$(document.ready(function(){
$('nav ul li').hover(function() {
// Stuff to do when the mouse enters the element
$(this).toggleClass('active');
});
});

Removing active class if clicking active link a second time?

I came across a question that wanted to add an active link to the currently clicked menu item.
The solution was to add:
$("a").click(function(){
$("a").removeClass("active");
$(this).addClass("active");
});
Now how can we remove the active class if we click the active link a second time? I'm guessing we need to use toggleClass() but I haven't been able to make it work. Note only one link should have active class at a time.
Here is a demo: http://jsfiddle.net/A6dqQ/
You can do:
$('a').click(function(e){
e.preventDefault();
var $a = $(this);
$a.toggleClass('active').siblings().removeClass('active');
});
Use toggleClass() then:
$(this).toggleClass("active");
Code:
$("a").click(function(){
$(this).toggleClass("active");
$("a").not(this).removeClass("active");
});
FIDDLE DEMO
Check if current link is active then add/remove active class based on that, Try this:
$("a").click(function(){
var $this = $(this);
var isActive = $this.hasClass('active');
$("a").removeClass("active");
isActive ? $this.removeClass("active") : $this.addClass("active");
});
jsFiddle
here you have a simple answer:
$("a").on("click", function() {
$("a").removeClass("active");
$(this).addClass("active");
});
$("nav").on("mouseleave", function() {
$("nav").find("a").removeClass("active");
});
What this does is, when your mouse leaves the nav it will automatically remove you active class on a. here you have the DEMO
Something like this?
$("a").click(function () {
var $this = $(this);
if ($this.hasClass("active")) {
$this.removeClass("active");
} else {
$("a").removeClass("active");
$this.addClass("active");
}
});
Fiddle

JQuery: .remove() does not work properly

Here is my html and codes :
<div id="rptCategoryProducts">
<ul class="productsUl">
</ul>
</div>
removing scritp :
$("#btnFilter").click(function () {
$(".productsUl li").each(function () {
this.remove();
});
currentPage = 0;
InfiniteScroll(0, 1000);
});
adding script:
$(".productsUl").append("<li>" + productInnerHtml + "</li>");
But it doesn't remove and also when I watch the steps in Mozilla Firebug I saw it stops after this.remove(); line.
Do you have suggestion?
or even simpler:
$(".productsUl li").remove();
;-)
You need to use $(this) to refer to the li element
$("#btnFilter").click(function () {
$(".productsUl li").each(function () {
$(this).remove();
});
currentPage = 0;
InfiniteScroll(0, 1000);
});
http://jsfiddle.net/Gwbmw/
When you loop through a jQuery object using each, you get the elements themselves, not each element wrapped in a jQuery object. You need to wrap each element in a jQuery object to use the remove method:
$(".productsUl li").each(function () {
$(this).remove();
});
However, you don't even need to loop through the elements, just use the remove method on the jQuery object containing all the elements:
$(".productsUl li").remove();
You need $(this) instead of this -
$(".productsUl li").each(function () {
$(this).remove();
});
You shoud try this:
$(this).remove();
instead of
this.remove();
Missing '$'. Try:
$(".productsUl li").each(function () {
$(this).remove();
});
In each callback, this points to the dom element reference not to the jquery object reference. So you need to get the jquery object reference of the item before calling remove()
$(".productsUl li").each(function () {
$(this).remove();
});
It can be done much easily
$(".productsUl > li").remove()
Strange. It works for me. look at this test:
[link]http://jsfiddle.net/bwqwD/

How to add a class onto the selected li element and make li full-sized-clickable

I want to add a class to the selected 'li' and at the same time, remove the class:selected from previous selected li element.
I have worked on it hours and still haven't got any luck. I also checked others questions, but their solutions don't work for me.
Help please....
<ul id='mainView' class='menu' style='float: left; clear: both;'>
<li>Patient</li>
<li>Recommendations</li>
</ul>
<script type="text/javascript">
$(document).ready(function () {
$('.menu ul a').on('click', function (event) {
$('.menu ul a.selected').className = '';
alert($(this).attr('id'));
$(this).attr('class') = 'selected';
});
});
// $('.menu li').on('click', function () {
// $('.menu li.selected').className = '';
// this.className = 'selected';
// });
</script>
Update:
I did put a inside li, but if I click on the li not the a inside of the li, the webpage does not redirect. That's the reason why I do it in a reversed way.
Update 2
The reason why the selected li does not get the "selected" class is because the whole webpage is redirected to a new page which has the same navigation bar.
So now the question is how to highlight the selected li(it was selected on the previous page) on the new webpage.
Inside an UL everybody (even a browser) is expecting to see a LI
so your HTML:
<ul>
<li>Patient</li>
<li>Recommendations</li>
</ul>
And your jQ:
$('ul li').click(function(){
$(this).addClass('selected').siblings().removeClass('selected');
});
Building web pages you should know how to treat LI elements. Simple, like dummy containers with minimal styling.
That means that you rather add a display:block ... float:left and other cool stuff to the <A> elements, than setting a padding there you go with your full-sized-clickable A elements.
Additionally (if you don't have time to play with CSS) to make a LI fully clickable use:
$('ul li').click(function(){
var goTo = $(this).find('a').attr('href');
window.location = goTo ;
// $(this).addClass('selected').siblings().removeClass('selected'); // than you don't need this :D
});
After the OP late edit - and to answer the question
After the pages refreshes to get which one is the active one use:
// ABSOLUTE PATH
var currentPage = window.location;
// RELATIVE PATH
// var currentPage = window.location.pathname;
$('li a[href="'+ currentPage +'"]').addClass('selected');
<script type="text/javascript">
$(document).ready(function () {
$('.menu ul a').on('click', function (event) {
$('.menu ul a.selected').removeClass('selected');
alert($(this).attr('id'));
$(this).addClass('selected')
});
});
</script>
Try addClass and removeClass, they're jQuery functions:
$(document).ready(function () {
$('.menu ul a').on('click', function (event) {
$('.menu ul a.selected').removeClass("selected");
$(this).addClass('selected');
});
});

Categories

Resources