Edit div class name on click - javascript

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

Related

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

Why classes change the order?

$("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");
});

How do I change the CSS for the sequential number element on click?

I have used jQuery to generate a sequential numbering for my menu items.
When clicked, the hyperlink text becomes red.
However, the problem here is that I want the respective number to turn into red as well when the hyperlink is clicked (active).
Such as when 'WHY YOU NEED IT' is clicked, the text turns red perfectly. But I need the number 1's background color to change into red as well.
I tried replacing classes but it didn't work.
This is the JS.
jQuery(function ($) {
$(".menu-solutions-menus-container ul li").each(function (i, el) {  $(this).children('a').prepend("<number>" + (i + 1.) + "</number>");
});
$('.local-scroll').click(function (event) {
event.preventDefault();
var full_url = this.href;
var parts = full_url.split('#');
var trgt = parts[1];
var target_offset = $('#' + trgt).offset();
var target_top = target_offset.top;
$('html, body').animate({
scrollTop: target_top
}, 500);
});
$('.menu-solutions-menus-container a').click(function () {
$('.menu-solutions-menus-container a').removeClass('active');
$(this).addClass('active');
});
$('.number').click(function () {
$('.number').removeClass('active');
$(this).addClass('active');
});
Here's the jsfiddle workspace. (Change jQuery version to jQuery 1.7.2 or above if you don't see the numbers.)
The secondary menu in this site is where I would really want to implement it.
Thanks a lot in advance.
Your class names just need a tweek and this'll work fine
change
number.active {
background: white;
}
To
.active number {
background: red;
}
Edit (explanation)
The CSS selector number.active is looking for an html element number that has a class of active like this <number class="active" /> but what your HTML shows is that you wanted the parent <a> to have the active with a child node of <number>.
So to do that you put the parent class first, followed by a space to note a child node of the parent, followed by the element you want to target.
so:
parentElement.parentClass childElement.childClass {
defs
}
you could write
a.active number {
background: red
}
Edit 2 for top bars:
There's a few things, the first being that the grey areas are actually background colors, as opposed to borders. Second the CSS selector is looking for a parent class of "active" but your "active" is a child of the <li>'s
<li id="menu-item-205" class="local-scroll menu-item menu-item-type-custom menu-item-object-custom menu-item-205">
</li>
what you can do is make the li the get the active class like this
$('.menu-solutions-menus-container a').click(function () {
$('.menu-solutions-menus-container a').removeClass('active');
$(this).parent('li').addClass('active');
});
$('.number').click(function () {
$('.number').removeClass('active');
$(this).parent('li').addClass('active');
});
$('.menu-solutions-menus-container a').click(function(){
$('ul.shortcode_menu.solution-menu li').removeClass('active');
$(this).parent('li').addClass('active');
});
Then change your CSS to reflect the <li> is the element with the active class.
ul.shortcode_menu.solution-menu li.active {
background: black;
}
Again I've changed it to background: black instead of border-top, as I think that's the effect you want.

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".

javascript set element background color

i have a little javascript function that does something when one clicks on the element having onclick that function.
my problem is:
i want that, into this function, to set a font color fot the html element having this function onclick. but i don't suceed. my code:
<script type="text/javascript">
function selecteazaElement(id,stock){
document.addtobasket.idOfSelectedItem.value=id;
var number23=document.addtobasket.number;
number23.options.length=0;
if (stock>=6) stock=6;
for (i=1;i<=stock;i++){
//alert ('id: '+id+'; stock: '+stock);
number23.options[number23.options.length]=new Option(i, i);
}
}
</script>
and how i use it:
<li id = "product_types">
<a href="#" onclick='selecteazaElement(<?= $type->id; ?>,<?= $type->stock_2; ?>);'><?= $type->label; ?></a>
</li>
any suggestions? thanks!
i have added another function (jquery one) that does partially what i need. the new problem is: i want that background color to be set only on the last clicked item, not on all items that i click. code above:
$(document).ready(function() {
$('.product_types > li').click(function() {
$(this)
.css('background-color','#EE178C')
.siblings()
.css('background-color','#ffffff');
});
});
any ideas why?
thanks!
I would suggest
$(document).ready(function() {
$('.product_types > li').click(function() {
$('.product_types > li').css('background-color','#FFFFFF');
$(this).css('background-color','#EE178C');
});
});
Your element could have this code:
<li id = "product_types" onclick="selecteazaElement(this);" <...> </li>
To change the foreground color of that element:
function selecteazaElement(element)
{
element.style.foregroundColor="#SOMECOLOR";
}
If you want to change the background color on only the last element clicked, each element must have a different id. I'd suggest naming each one something like product_types1, product_types2, ..., product_typesN, and so on. Then have a reset function:
function Reset()
{
for (var i = 1; i <= N; i = i + 1)
{
document.getElementById('product_types'+i).style.backgroundColor="#RESETCOLOR";
}
}
When you call your selecteazaElement(this) function, first call the Reset function, then set the new element:
function selecteazaElement(element)
{
Reset();
element.style.backgroundColor="#SOMECOLOR";
}
This way all of the elements that start with product_types followed by a number will be reset to one particular color, and only the element clicked on will have the background changed.
The 'scope' of the function when invoked is the element clicked, so you should be able to just do:
function selecteazaElement(id,stock){
document.addtobasket.idOfSelectedItem.value=id;
var number23 = document.addtobasket.number;
number23.options.length=0;
if (stock>=6){
stock=6;
}
for (var i=1;i<=stock;i++){
//alert ('id: '+id+'; stock: '+stock);
number23.options[number23.options.length]=new Option(i, i);
}
// Alter 'this', which is the clicked element in this case
this.style.backgroundColor = '#000';
}
$(function() {
/*if product_types is a class of element ul the code below
will work otherwise use $('li.product_types') if it's a
class of li elements */
$('.product_types li').click(function() {
//remove this class that causes background change from any other sibling
$('.altBackground').removeClass('altBackground');
//add this class to the clicked element to change background, color etc...
$(this).addClass('altBackground');
});
});
Have your css something like this:
<style type='text/css'>
.altBackground {
background-color:#EE178C;
/* color: your color ;
foo: bar */
}
</style>
Attach a jQuery click event to '#product_types a' that removes a class from the parent of all elements that match that selector; then, add the class that contains the styles you want back to the parent of the element that was just clicked. It's a little heavy handed and can be made more efficient but it works.
I've made an example in jsFiddle: http://jsfiddle.net/jszpila/f6FDF/
try this instead:
//ON PAGE LOAD
$(document).ready(function() {
//SELECT ALL OF THE LIST ITEMS
$('.product_types > li').each(function () {
//FOR EACH OF THE LIST ITEMS BIND A CLICK EVENT
$(this).click(function() {
//GRAB THE CURRENT LIST ITEM, CHANGE IT BG, RESET THE REST
$(this)
.css('background-color','#EE178C')
.siblings()
.css('background-color','transparent');
});
});
});
If I am correct, the problem is that the click event is being binded to all of the list items (li). when one list item is clicked the event is fired on all of the list items.
I added a simple .each() to your code. It will loop through each of the list items and bind a event to each separately.
Cheers,
-Robert Hurst

Categories

Resources