Why classes change the order? - javascript

$("body").on("click", ".close", function() {
var class_test1 = 'class1 class2';
var class_test2 = 'class1 class3';
$('#id_test').removeClass(class_test1).addClass(class_test2);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="id_test" class="class1 class2">
test
</div>
<button class="close">
test
</button>
If click on button, div#id_test should be change classes on class1 class3, but he change classes on class3 class1(classes change the order).
Why is this happening and have resolved problem?
P.S.: need change class1 class3 on class1 class2 - only in this order.

The reason is the following:
There are multiple classes overlapping with multiple clicks.
Let me explain:
When you click the button the first time, the classes "class1" and "class2" get removed. Then "class1" and "class3" gets attached.
However, if you click the button AGAIN, ONLY "class1" gets removed, making "class3" move to the first position (since there is no "class2" to remove anymore). Then "class1" gets re-added AFTER "class3" - resulting in "class3 class1".
Suggested solution:
$("body").on("click", ".close", function() {
var class_test2 = 'class1 class3';
$('#id_test').removeClass().addClass(class_test2);
});
This will remove ALL the classes and then adds the right ones in right order.

You can use .toggleClass() to toggle 2 , 3 at end of one of the className string
$("body").on("click", ".close", function() {
var n = 3;
$("#id_test").toggleClass(function() {
return "class2 class" + n;
})
});
#id_test.class2 {
color: green;
}
#id_test.class3 {
color: blue;
}
#id_test.class2:after {
content: attr(class);
}
#id_test.class3:after {
content: attr(class);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<div id="id_test" class="class1 class2">
test
</div>
<button class="close">
test
</button>

try
$(".close").on("click", function() {
$('#id_test').removeClass("class2").addClass("class3");
});

Related

Add class to next integer on click while removing from current jQuery

I am wrapping the class; slideVisible to the first 3 blog articles displayed. This class removes the css property; display - none. I have added some indicators with the class; carousel-buttons, which also is based on the number of loops of sets of 3 blog posts. On click of these carousel-buttons I would like to remove the class slideVisible from the element which currently has it, and then add to the next element in the sequence.
I have used an index-related selector to demonstrate a way of creating this function, however this is not dynamic. How would I do this correctly?
jQuery(document).ready(function() {
var carosuelPost = jQuery(".post-slider-mango .post");
jQuery('.post-slider-mango .fusion-posts-container').wrapAll('<div id="dog-slider"><div class="carousel-inner"></div></div>');
for (var i = 0; i < carosuelPost.length; i += 3) {
let activeClass = '';
if(i == 0) activeClass = 'slideVisible';
carosuelPost.slice(i, i + 3).wrapAll('<div class="slideElements ' + activeClass + '"> </div>');
}
for (var i = 0; i < carosuelPost.length; i += 3) {
if(i == 0) activeClass = 'slideVisible';
jQuery(".post-slider-mango .fusion-posts-container").after('<a class="carousel-buttons"><li></li></a>');
jQuery(".carousel-buttons:eq(0)").on("click", function() {
jQuery(".slideElements").removeClass("slideVisible");
jQuery(".slideElements:eq(0)").addClass("slideVisible");
});
jQuery(".carousel-buttons:eq(1)").on("click", function() {
jQuery(".slideElements").removeClass("slideVisible");
jQuery(".slideElements:eq(1)").addClass("slideVisible");
});
}
});
So it's hard to say because it depends on the element that has the activeClass class and the heirarchy. You can have the .carousel-button on click remove the class from its parent, or parent's parent.
You can use .closest() to find the closest ancestor with x class. So:
// Declare function that removes a given class from given element
// Set click event listener for .carousel-button elements
$('.carousel-button').click(function(e){
e.preventDefault();
$(this).closest('div.slideVisible').removeClass('slideVisible');
});
Also to note, I would use a <button> element for the carousel-button so you do not then need to use the e.preventDefault() in the click event. If it is only to be used to run JavaScript via user interaction then you do not need to use an <a> tag.
See snippet for working example.
// Set click event listener for .carousel-button elements
$('.carousel-button').click(function(){
const next = $(this).closest('div.slideVisible').next().is('.slide');
if (next) {
return $(this).closest('div.slideVisible').removeClass('slideVisible').next().addClass('slideVisible');
} else {
return $(this).closest('div.slideVisible').removeClass('slideVisible').prev().addClass('slideVisible');
}
});
.slide {
display:none;
padding:2rem;
text-align:center;
background:orange;
}
.slide2 {
background:yellow;
}
.slideVisible {
display:block;
}
.carousel-button {
padding:1rem;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="slide slide1 slideVisible">
<div class="buttons">
<button class="carousel-button">Hide Me!</button>
</div>
</div>
<div class="slide slide2">
<div class="buttons">
<p>This is slide 2</p>
<button class="carousel-button">Hide Me!</button>
</div>
</div>
Edit: This answer assumes that you're trying to remove the class from a parent of the button you're clicking. If you need to get it from the sibling before or after you can use .prev() and .next() after calling the .closest() method:
$(this).closest('div.slideVisible').prev().removeClass('slideVisible');

Edit div class name on click

So basically I have a bunch of nav buttons that I want to change the name of when the user clicks the button.
The original div class name is something like "home", and when the user clicks on it I want it to be "home_active" so that the CSS attributes will change the background-image.
$('.click').click(function() {
var clicked_url = $(this).attr('class');
var updated_url = clicked_url + "_active";
$(this).attr('class') = updated_url;
});
.item_active {
background-color: teal;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
item 1
item 2
item 3
You shall use the .addClass() method add a class to the element:
$('.click').click(function() {
var clicked_url = $(this).attr('class');
var updated_url = clicked_url + "_active";
$(this).removeClass(clicked_url); // remove the old class
$(this).addClass(updated_url); // add the new class
});
However, as a good practice, it is better to add a modifier class, such as "active" to the existing class, preserving the original class name.
Then use the following CSS:
.click.active {
background: red;
}
The JS code would look like this:
$('.click').click(function() {
$('.click.active').removeClass('active'); // remove active class from all other nav items
$(this).addClass('active'); // add active to the nav item the users just clicked on
});
Using Jquery functions:
$(this).hasClass("className");
$(this).addClass("className");
$(this).removeClass("className");
$('.click').click(function() {
var clicked_url = $(this).attr('class');
var updated_url = clicked_url + "_active";
$(this).removeClass(updated_url)
$(this).addClass(updated_url)});
Almost there - but remember to use attr to reset the class value. And you most likely want to remove _active from the other .click elements, so this is the only one.
$(".click").click(function() {
$(".click").each(function() {
$(this).attr("class", $(this).attr("class").replace(/_active/, ""));
});
$(this).attr("class", $(this).attr("class") + "_active");
});
Not sure where class .click is but there is .item and .click(...) method is ok -- I prefer to use .on('click', ...) (see the difference between .click() and .on()).
$('.item').on('click', function() {...
Since objective is to simply change the style of a clicked link by changing its class then it's better to assign a common class (which was done: .item) and a class that sets the state (a separate class: .active).
$(this).toggleClass('active');
If you wish to apply this to additional tags, simply modify the outer selector
$('.item, :button').on('click', function() {...
The selector above will listen for clicks on anything with the class .item and any <button> and <input type='button'> tags.
It wasn't very clear what the desired behavior was so there's two demos:
Demo 1: Click any link to add/remove .active class
or
Demo 2: Click any link to add/remove .active class exclusively
Demo 1
Click any link to add/remove .active class
$('.item').on('click', function() {
$(this).toggleClass('active');
});
.active {
background-color: teal;
color: white
}
item 1
item 2
item 3
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Demo 2
Click any link to add/remove .active class exclusively
$('.item').on('click', function() {
$(this).toggleClass('active');
$('.item').not(this).removeClass('active');
});
.active {
background-color: teal;
color: white
}
item 1
item 2
item 3
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Couple things. First, you want to select elements with a class name of "item," not "click." Secondly, you were using the attr() function wrong. Instead of attr('class') = var, you want to set the var as the second parameter, e.g. attr('class', var).
Edit: Finally, you should check in your click event whether or not the link has been previously clicked (i.e. whether it already has the "_active" suffix):
$('.item').click(function() {
var clicked_url = $(this).attr('class');
var updated_url;
if(clicked_url.includes("_active")){
updated_url = "item";
}else{
updated_url = "item_active";
}
$(this).attr('class', updated_url);
});
.item_active {
background-color: teal;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
item 1
item 2
item 3

Switch CSS class everytime user clicks - Jquery

I have 2 links with different CSS classes.
How can I switch between the two everytime a the user clicks?
<a class="class1" id="class1">Class1</a>
<a class="class2" id="class2">Class2</a>
It's just work one time, but when I click a second time, it doesn't work:
$("#class1").click(function(){
$("#class1").removeClass().addClass("class2");
$("#class2").removeClass().addClass("class1");
})
$("#class2").click(function(){
$("#class1").removeClass().addClass("class2");
$("#class2").removeClass().addClass("class1");
})
The CSS is to change the color
The methods are doing the same thing. You set the same class to each tag in both thats why it only works the first time. The second time it just resetting the current class.
Shouldn't they be like this instead?
$("#class1").click(function(){
$("#class1").removeClass().addClass("class2");
$("#class2").removeClass().addClass("class1");
})
$("#class2").click(function(){
$("#class1").removeClass().addClass("class1");
$("#class2").removeClass().addClass("class2");
})
You can use toggleClass to switch multiple classes..
$('.red,.blue').click(function() {
$(this).toggleClass('red blue');
});
.red { background-color:red }
.blue { background-color:blue }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="red">One</div>
<div class="blue">Blue</div>
You can use selector "[class^=class]" to select elements where Element.className begins with "class"; use .slice() with parameters 0, -1 to select characters in string up to last character; check if last character is 1 or 2 using == equal operator; set the opposite last character for matches 1: "2", 2: "1" at last character of Element.className
$("[class^=class]").click(function() {
var c = this.className;
this.className = c.slice(0, -1) + (c[c.length - 1] == 1 ? 2 : 1);
});
.class1 {
color: blue;
}
.class2 {
color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="class1" id="class1">Class1</a>
<a class="class2" id="clas2">Class2</a>
Done using toggleClass JSFIDDLE:https://jsfiddle.net/kameeshwaran/5puecqeq/
HTML:
<a class="class1" id="class1">Class1</a>
<a class="class1" id="class2">Class2</a>
JS
$(document).ready(function(){
$(".class1").click(function(e){
e.preventDefault();
$(this).toggleClass("class2")
});
});
CSS:
.class1{
background-color:green;
}
.class2{
background-color:red;
}
When you click class1 once, it removes the class class1 from class1, and puts class2 on.
However, when you click it again, because class1 is set to the class class2, it won't change.
You should probably do something like this:
var class1check = 0;
$("#class1").click(function() {
if (class1check === 0) {
var addclass1 = "class2";
var addclass2 = "class1";
}
else {
var addclass1 = "class1";
var addclass2 = "class2";
class1check = 0;
}
$("#class1").removeClass().addClass(addclass1);
$("#class2").removeClass().addClass(addclass2);
});

Apply css settings to all clickable elements

I want to apply cursor: pointer; to any element that has jQuery click() function bound to it.
How can I do this without going to each element in my CSS file and manually adding cursor: pointer; to it? (I have a lot of various clickable items)
<span class = "clickable1">something</span>
<span class = "clickable2">something</span>
<span class = "clickable3">something</span>
$(".clickable1").click(function(){
//do something
});
$(".clickable2").click(function(){
//do something
});
$(".clickable3").click(function(){
//do something
});
You actually can do this.
By checking the internal $._data you can get the bound events on any element, then it's just a matter of checking if click is one of those events and attaching the style etc.
$('*').filter(function() {
var d = $._data( this, "events" );
return d && 'click' in d;
}).css('cursor', 'pointer');
FIDDLE
Add another class called isclickable so you would have
<span class = "isclickable clickable1">something</span>
<span class = "isclickable clickable2">something</span>
<span class = "isclickable clickable3">something</span>
Then you can have .isclickable { cursor: pointer; } in your css
Solution 1: give every clickable element the same class like
<span class = "clickable clickable1">something</span>
<span class = "clickable clickable2">something</span>
<span class = "clickable clickable3">something</span>
Solution 2: expand jQuery selector $(".clickable1, .clickable2, .clickable3")
Why not add a common class to all of them?
<span class = "clickable clickable1">something</span>
<span class = "clickable clickable2">something</span>
<span class = "clickable clickable3">something</span>
Then, with css:
.clickable {
cursor: pointer;
}
If you'd rather not change the HTML you already have manually (or if you can't), you can add the class when binding the event handlers:
function addClickBehavior($el, callback) {
return $el.addClass("clickable").on("click", callback);
}
addClickBehavior($(".clickable1"), function(){
//do something
});
addClickBehavior($(".clickable2"), function(){
//do something
});
addClickBehavior($(".clickable3"), function(){
//do something
});
Simply use a selector that selects all elements whose class name starts with "clickable":
$("*[class^='clickable']").css('cursor', 'pointer').click(function(){
//do something
});
BTW: Seems like a very "inefficient" use of the class attribute and class names aren't very "useful".

jquery mutiple div with a single definition script

i have this jQuery code:
$(document).ready(function () {
$("#hide").click(function () {
$("div1").hide();
});
$("#show").click(function () {
$("div1").show();
});
});
and this jsp/html
for{int=0;i<V_loopnumber;i++)
{
%>
<button id='show' height:10px>showit</button>
<div1>
something
<button id='hide' height:10px>hideit</button>
</div1>
<%
}
For example if I have 3 elements, it produces 3 divs. However,if I push the button all the divs will be showed or hided cause they got the same name.
how can I differentiate the button with the respective divs?
Your markup has a few problems. You can not assign the same ID twice. Also div1 is not a valid tag name.
Perhaps you can restructure your markup along the lines of the following example:
<div class="container">
<button class="show">showit</button>
<div class="inner">
something
<button class="hide">hideit</button>
</div>
</div>
I assigned the buttons classes instead of ids and got rid of the div1 elements.
Now you can listen for a click event on the buttons and hide the related elements using the .closest() (http://api.jquery.com/closest/) method like this:
$(".hide").click(function () {
$(this).closest(".inner").hide();
});
$(this).closest(".inner") will retrieve the the closest element with the class inner up in the dom tree.
$(".show").click(function () {
$(this).parent().find(".inner").show();
});
$(this).parent().find(".inner") will go up one level in the dom tree and find the element with the class inner.
http://jsfiddle.net/KGk7B/
First, element ids must be unique. Use a class instead. Second, <div1> isn't a valid tag. Use a div with a class instead. Third, use traversal functions to find the specific element to toggle.
$(document).ready(function () {
$(".hide").click(function () {
$(this).closest('.show-hide-container').hide();
});
$(".show").click(function () {
$(this).next('.show-hide-container').show();
});
});
for{int=0;i<V_loopnumber;i++)
{
%>
<button class='show' height:10px>showit</button>
<div class="show-hide-container">
something
<button class='hide' height:10px>hideit</button>
</div>
<%
}
id must be unique on your page, use class
<button class='show' height:10px>showit</button>
and use $(this) in event callback function instead of using selector
$(".hide").click(function(){
$(this).parent().hide(); // this is hard select of your div1, i wrote only for your html
});
IMPORTANT: Use div instead of div1, div1 tag is undefined.

Categories

Resources