Jquery - How to get elements in a list item - javascript

I have the following code:
<li class="shop-currencies">
€
£
$
R
</li>
When an item is clicked I want to set the class to the clicked item and get the ID of the item clicked. This is what I have so far:
$('.shop-currencies').click(function() {
var id = $(this).attr('id');
alert(id);
/**
* Remove the classes from the currency elements
*/
$('.shop-currencies').find('a').each(function(e) {
$(this).removeClass();
});
/**
* Set the class of the clicked element
*/
$( '#' + id).addClass('current');
});
The ID is being returned as 'undefined' How do I get the ID of the clicked link?
Thanks

You need to attach click handler to child anchor element :
$('.shop-currencies a').click(function() {
var id = $(this).attr('id');
alert(id);
/**
* Remove the classes from the currency elements
*/
$('.shop-currencies').find('a').not(this).removeClass('smclass')
/**
* Add class to current elements
*/
$(this).addClass('smclass')
});

There are a couple of options, Milind Anantwar has one, the other is to use the originally clicked element, which is passed to the event as a target property on the event argument. You can also simplify your code a lot. Please note that your bookmark anchors will cause the page to spring to the top, so also add e.preventDefault(); to any solution you choose:
$('.shop-currencies').click(function(e) {
e.preventDefault();
$('a', this).removeClass('current'); // remove related anchor current class
$(e.target).addClass('current');
});
JSFiddle: http://jsfiddle.net/TrueBlueAussie/5Lsuazvt/
The one downside to this is that clicking inside .shop-currencies, but not on a currency link, will clear the current selection. Because of this you are better off targetting the links instead:
$('.shop-currencies a').click(function(e) {
e.preventDefault();
$(this).siblings().removeClass('current'); // remove related anchor current class
$(this).addClass('current');
});
JSFiddle: http://jsfiddle.net/TrueBlueAussie/5Lsuazvt/1/
Which can be reduced to one line:
$('.shop-currencies a').click(function(e) {
e.preventDefault();
$(this).addClass('current').siblings().removeClass('current');
});
JSFiddle: http://jsfiddle.net/TrueBlueAussie/5Lsuazvt/2/
Saving the best for last
And one last point... It is more efficient (but hardly noticeable) to add a single delegated event handler, instead of attaching 4 seperate handlers:
$('.shop-currencies').on('click', 'a', function(e) {
e.preventDefault();
$(this).addClass('current').siblings().removeClass('current');
});
JSFiddle: http://jsfiddle.net/TrueBlueAussie/5Lsuazvt/3/
Final thoughts:
The IDs on the links are unnecessary if you have an appropriate this available. You can remove them from the HTML. You have the currency value you require in data-currency attributes, so you could use it like this:
$('.shop-currencies').on('click', 'a', function(e) {
e.preventDefault();
$(this).addClass('current').siblings().removeClass('current');
alert($(this).data('currency'));
});
JSFiddle: http://jsfiddle.net/TrueBlueAussie/5Lsuazvt/7/

your click, is attach to li instead of each a tag
so do $('a').click();instead

Shortest and fastest answer
$('.shop-currencies > a').click(function(){
$(this).siblings('a').removeClass('current');
$(this).addClass('current');
});
The code pen link is here, you can play with the code your self

$('.shop-currencies a').each(function() {
$(this).on("click", function(event) {
event.preventDefault();
var id = $(this).attr('id');
$('.shop-currencies a').removeClass("current");
$(this).addClass('current');
alert(id);
});
});
http://jsfiddle.net/nj37g5rm/8/

Related

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

Add class to several elements

I have a cloned element and I want it so if I add a class to one of them it checks for active removes is and adds it to this and translates to the other. Here's what I'm working with:
$(document).ready(function() {
$("li").click(function(){
/*Here I want to add something like var active = $(.clonedelement + this, this)
but that does probably not makes sense, so what should i do? */
var active = $(this)
// If this isn't already active
if (!$(this).hasClass("active")) {
// Remove the class from anything that is active
$("li.active").removeClass("active");
// And make this active
active.addClass("active");
}
});
});
Right now, it removes the current active from both, not does only add class to one.
I made a jsfiddle of it
http://jsfiddle.net/pintu31/8BxuE/
function UpdateTableHeaders() {
$(".persist-area").each(function() {
var el = $(this),
offset = el.offset(),
scrollTop = $(window).scrollTop(),
Header = $("#headerny", this)
if ((scrollTop > offset.top) && (scrollTop < offset.top + el.height())) {
Header.addClass("floatingHeader");
} else {
Header.removeClass("floatingHeader");
};
});
}
// DOM Ready
$(function() {
$(window)
.scroll(UpdateTableHeaders)
.trigger("scroll");
});
If you just need to highlight the clicked element with the class of active, and remove all others then try this:
$("li").click(function(){
$("li").removeClass("active");
$(this).addClass("active");
});
You don't really need to check if either this, or others already have the class, simply steamroller to 'active' class off all the others and add it to the one that's been clicked
try this
demo updated 1
demo updated 2 //with clone(true)
demo updated 3 //with clone(false) - default
demo updated 4
$(document).ready(function() {
$(document).on('click', 'li', function(){
var ind = $(this).index();
$('li').removeClass('active');
$('li').eq(ind).addClass('active');
$('#header1').empty();
$('#header').find('ul').clone(true).appendTo( '#header1' );
});
});
$(document).ready(function() {
$("li").click(function(){
$("li").removeClass("active");
// And make this active
$(this).addClass("active");
}
});
});

click elsewhere

i have problem with click event. click to another element with event(click), doesn't count like click elsewhere. I want active one element or none.
demo: http://jsfiddle.net/WP4RH/
code:
$('span').click(function(){
var $this = $(this);
if($this.hasClass('active')){
$this.removeClass('active')}
else $this.addClass('active');
$('div').click(function(){
if (!$this.has(this).length) {
$this.removeClass('active');
}
});
return false;
});
Add this at the beginning of your span event handler:
$('.active').removeClass('active');
Demo
This is assuming that you want multiple clicks on the same span to retain active. If you don't want that, then let me know and I can modify the code.
​
For starters, You should move the div handler outside and then removeClass based on div element.
$('span').click(function(e) {
e.stopPropagation();
$(this).parent().find('span').removeClass('active');
$(this).toggleClass('active');
});
$('div').click(function() {
$(this).find('span').removeClass('active');
});
DEMO: http://jsfiddle.net/WP4RH/1/
Don't bind a click handler inside a click handler, just check if the target is the div or the span inside the click handler instead. Also, when adding the active class to this, just remove it on any sibling span :
$('span').on('click', function(){
$(this).toggleClass('active').siblings('span').removeClass('active');
});
$('div').on('click', function(e){
if (e.target == this) $('span').removeClass('active');
});
FIDDLE
​
If you want to keep the toggle-off functionality when the span itself has been clicked, then you can use the following. Also, note that you're binding an event handler each time a span is clicked.
http://jsfiddle.net/WP4RH/7/
$("span").click(function() {
$(this).siblings("span").removeClass("active"); // remove from other spans
$(this).toggleClass("active"); // toggle this span
return false;
});
​
$("div").click(function() {
$(this).find("span").removeClass("active"); // remove from all spans
});

JQuery add class on current item

I have this method that changes an larger image source on click.
I need to add a 'current' class on the selected. I have no problem adding this class,but I need it to remove the class on the other, previous, selected item.
This is the code I'm using at the moment:
$(document).ready(function() {
$("ul.timgs li a").click(function(e) {
e.preventDefault();
var path = $(this).attr("href");
$("div.tour-image img").attr({"src": path});
});
});
Thanks :-)
This should work:
$("ul.timgs li a").click(function(e) {
$(".current").removeClass("current");
$(this).addClass("current");
...
}
Before you add the "current" class to the new current item, remove it from the previous current item:
$(".current").removeClass("current");

Categories

Resources