Change element id and behaviour on click - javascript

I need to make a button that changes its id on click, and its name. It changes only when I click the first time on "Start!". After that it is not working and I don't know why.
$("#start").click(function(){
$(this).attr("id", "stop");
$(this).html("Stop!");
});
$("#stop").click(function(){
$(this).attr("id", "start");
$(this).html("Start!");
});

Changing ID is not a good idea.
have a button and toggle the class and content
$("#toggle").on("click",function(){
$(this).toggleClass("stop");
$(this).html($(this).is(".stop")?"Stop":"Start"); // if ($(this).is(".stop")) {} else {}
});
.stop { background-color:red }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="toggle">Start</button>

The $('#stop') selector can't works because you have no html element with the id stop when you run it. So you have 2 choices : Use only one listener or use the delegation system of jQuery.
One listener :
$('#start').click(function() {
var $this = $(this),
id = $this.attr('id');
if (id == 'start') {
$this.attr('id', 'stop');
$this.html('Stop!');
} else {
$this.attr('id', 'start');
$this.html('Start!');
}
});
Delegation system :
$(document.body).on('click', "#start", function(){
$(this).attr("id", "stop");
$(this).html("Stop!");
});
$(document.body).on('click', "#stop", function(){
$(this).attr("id", "start");
$(this).html("Start!");
});
Anyway, mplungjan is right. Changing the ID is not a good idea. You should use a CSS class for that.

Related

Toggle inline CSS in jQuery

I want to toggle some inline CSS with a jQuery script, but I can't do it with a class, because I get the value of the padding-top dynamically, here is the function :
$('.button').click(function(){
$(this).toggleClass('active');
});
var tagsHeight = $('span').outerHeight();
$(".button").click(function (){
if ($(this).is('active')) {
$(".change").css('padding-top', '0');
}
else if ($(this).not('active')) {
$(".change").css('padding-top', tagsHeight);
}
});
An a example here : https://jsfiddle.net/o1pbwfuo/
I really don't get why this is not working correctly ...
Thanks !
The issue with your code is due to the incorrect selector in not(). That being said, you can improve your logic by combining the click() event handlers, then using a single ternary expression to set the padding-top on the required element based on the related class. Try this:
var tagsHeight = $('span').outerHeight();
$('.button').click(function() {
var active = $(this).toggleClass('active').hasClass('active');
$(".change").css('padding-top', !active ? '0' : tagsHeight);
});
Working example
You made a mistake while using .is and .not.
You need to address the class itself inclusive the dot at beginning.
$('.button').click(function(){
$(this).toggleClass('active');
});
var tagsHeight = $('span').outerHeight();
$(".button").click(function (){
if ($(this).is('.active')) {
$(".change").css('padding-top', '0');
}
else if ($(this).not('.active')) {
$(".change").css('padding-top', tagsHeight);
}
});
https://jsfiddle.net/06ek4fej/
By the way, the else-if request is nonsense.
If = true or if = false. Else If results the same as else.
$(".button").click(function (){
if ($(this).is('.active')) {
$(".change").css('padding-top', '0');
}
else {
$(".change").css('padding-top', tagsHeight);
}
});
On click you can check whether element has active class or not and there is no need to add two click methods on '.button'.
var tagsHeight = $('span').outerHeight();
$(".button").click(function (){
$(this).toggleClass('active');
if ($(this).hasClass('active')) {
$(".change").css('padding-top', '0');
}
else{
$(".change").css('padding-top', tagsHeight);
}
});
You can use Has class method for the check is active class exist or not.
$(".button").click(function (){
if ($(this).hasClass('active')) {
$(".change").css('padding-top', '0');
}
else{
$(".change").css('padding-top', tagsHeight);
}
});

Jquery - How to get elements in a list item

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/

JQuery- Change the id of an element and call a function on click

I have an element with some id, I changed its ID and when I click on that element (with new ID now), it still calls the function with previous ID
$('#1st').click(function(){
$('#1st').attr('id','2nd');
alert("id changed to 2nd");
});
$('#2nd').click(function(){
alert("clicked on second");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Click
Example is here
Because you add the event before the element exists. It does not find an element. Either attach the event when you change the id or you need to use event delegation.
$('#1st').on("click.one", function(e) {
$('#1st').attr('id', '2nd');
alert("id changed to 2nd");
e.stopPropagation();
$(this).off("click.one");
});
$(document).on("click", '#2nd', function() {
alert("clicked on second");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Click
Try doing it this way jsFiddle
$(document).on('click', '#2nd', function(){
alert("clicked on second");
})
.on('click', '#1st', function(e) {
$('#1st').attr('id','2nd');
alert("id changed to 2nd");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Click
Also see this post on using Jquery's .on() versus .click()

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
});

Categories

Resources