I need one help. I need to add one new class along with the existing class using Jquery/Javascript. I am explaining my code below.
<div class="fynd-space-itms">
<div class="col-sm-3">
Ram</div>
<div class="col-sm-3">
Raj</div>
<div class="col-sm-3">
Ray
</div>
</div>
Here I need when user will click on the onclick event one new class will add along with existing class. Suppose user clicked on Ram and after clicking the new class i.e-active will add and the total class name will be item-exhibitationactive maploc and same for others i.e-item-parkingactive maploc,item-officesactive maploc. At the same time from other anchor tag the active class will remove if it added before. Please help me.
In jquery try this:
$('.maploc').click(function(){
$('.maploc').removeClass('active'); // to remove already added class
$(this).addClass('active');
});
Working Fiddle
function keepSection($this){
var className=$($this).attr('class').replace('maploc','').replace(' ','');
var newclassName = className +'active';
//alert(className);
$('a').each(function(){
var theirClass= $(this).attr('class');
var patt = new RegExp("active");
if(patt.test(theirClass))
{
$(this).removeClass(theirClass);
var newCls = theirClass.replace('active','');
$(this).addClass(newCls);
}
});
$($this).removeClass(className);
$($this).addClass(newclassName);
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-sm-3">
Ram
Raj
Ray
</div>
<div class="col-sm-3">
Ram1
Raj1
Ray1
</div>
If you are trying to have differant active states for the items, you can just use
Sorry, first answer, have updated with snippet
$('.maploc').click(function(e){
e.preventDefault();
// Save DOM element to a var for speed.
var self = $(this),
// Get the first class name from the attr
active = self.attr('class').split(" ")[0],
// Set inactive to be the same as active
inactive = active;
// Remove maploc class so we only have 1 class left to work with
self.removeClass('maploc');
// Is active already active?
if(active.match(/active/g)) {
// YES : Remove active from the class
inactive = active.replace(/active/,'');
} else {
// NO : Append active to the class
active = active+'active';
}
// Toggle between active and inactive
self.toggleClass(active +" "+ inactive);
// Append maploc back into the class attr
self.addClass('maploc');
// Next line not needed.
$('#class').text(self.text() + '=' + self.attr('class'));
});
.item-exhibitationactive{
color:red;
}
.item-parkingactive {
color:yellow;
}
.item-officesactive {
color:green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-sm-3">
Ram
Raj
Ray
</div>
<div><b>Current Class:</b> <span id="class"></span>
Related
I'm working with three tabs called 'Monday', 'Tuesday' and 'Favorites'. I have a toggle icon which is an empty heart at start 'favorite i'. If I'm in Monday and click on the icon, the empty heart turns to be filled out and its parent is cloned and added to the '#fav' tab. When this happens the clone is saved to local storage. So if people refresh the page, they can still see their preferences.
When the heart is clicked in one of those cloned divs that specific div is removed from '#fav' and is also removed from the array.
Everything works well, except when I refresh the browser and local storage is detected.
So, in this case if I'm in Monday and click on a filled heart it doesn't remove the clone from #fav and still adds a new clone to #fav. Also, if I'm in #fav tab, when clicking in one of the hearts, it should erase the index from the array, but in fact, it erases the full array.
How to overcome this issue? Many thanks.
HTML:
<section id="speakers-programme">
<div class="container">
<div class="tabs_main">
<div class="col-md-5"><a data-target="#mon" class="btn active" data-toggle="tab">Monday</a></div>
<div class="col-md-5"><a data-target="#tue" class="btn active" data-toggle="tab">Tuesday</a></div>
<div class="col-md-2"><a data-target="#fav" class="btn active" data-toggle="tab"><i class="fa fa-heart" aria-hidden="true"></i></a></div>
</div>
<div class="tab-content">
<div class="tab-pane active" id="mon">
<br>
<div class="spaces">
<div class="box-container">
<div class="box not-selected" id="box1">
<span>1</span>
<i class="fa fa-heart-o" aria-hidden="true"></i>
</div>
</div>
<div class="box-container">
<div class="box not-selected" id="box2">
<span>2</span>
<i class="fa fa-heart-o" aria-hidden="true"></i>
</div>
</div>
</div>
</div>
<div class="tab-pane active" id="tue">
<br>
<div class="spaces">
</div>
</div>
<div class="tab-pane active" id="fav">
<br>
<div class="spaces">
</div>
</div>
</div>
</div>
</section>
JS
console.clear();
//localStorage.setItem('sessions', "");
var tempArray = [];
// Clones
$('div.tab-pane').on('click', '.favorite', function(e) {
e.preventDefault();
// Elements we play with... Having significative variable names.
var heartLink = $(this);
var box = heartLink.parent('.box');
var container = box.parent('.box-container');
var favoriteTab = $("#fav .spaces");
// I don't know what is the use for those 3 lines below.
var idFind = box.attr("id");
var idComplete = ('#' + idFind);
console.log(idComplete);
//TOGGLE FONT AWESOME ON CLICK
heartLink.find('i').toggleClass('fa-heart fa-heart-o'); // .selected or not, you need those 2 classes to toggle.
box.toggleClass("selected not-selected"); // Toggle selected and not-selected classes
// Clone div
var boxContent = container.clone(true, true);
// Change the id
var thisID = boxContent.attr("id")+"_cloned";
boxContent.attr("id", thisID);
// Get the html to be saved in localstorage
var get = boxContent.wrap('<p>').parent().html();
get = get.replace(/\r?\n/g, "").replace(/>\s*</g, "><"); // remove line feeds and spaces
console.log(get);
boxContent.unwrap();
// Decide to add or remove
if(box.hasClass("selected")){
console.log("Add to array")
tempArray.push(get);
// Add to favorites tab
favoriteTab.append(boxContent);
}else{
console.log("Remove from array");
var index = tempArray.indexOf(get);
tempArray.splice(index);
// Remove from favorite tab
favoriteTab.find("#"+thisID).remove();
}
// Save array
localStorage.setItem('sessions', tempArray.join(""));
console.log(tempArray);
// save this current toggle state
localStorage.setItem(box.attr("id"), $(this).find("i").attr("class"));
console.log($(this).find("i").attr("class"));
});
// Append item if localstorage is detected
if (localStorage["sessions"]) {
console.log("storage exist");
// Load
$(".box").each(function(){
console.log( $(this).attr("id") );
console.log( localStorage.getItem($(this).attr("id")) );
if(localStorage.getItem($(this).attr("id")) != null){
$(this).find("i").removeClass().addClass( localStorage.getItem($(this).attr("id")) );
}
});
$("#fav .spaces").append(localStorage["sessions"]);
console.log( localStorage["sessions"] );
}
Fiddle: https://codepen.io/Bes7weB/pen/bobjdv?editors=1011
I twisted your code in a way that deserves explanations.
First, you finally don't need to save the HTML of your favorited elements. You just need the heart icon states, which you already do. I added a counter, just to know how many favorited there is in storage.
Now, on page load... If there is more than zero favorites in storage, Apply the icon states by loading their classes from storage. You already had this part right. THEN cycle throught all hearts to target the filled ones and clone them in the favorite tab. I made a "named function" to do this.
On icon click now... Clicking on a cloned element or on an original element are two different situations.
On an original element, you want to toggle its classes and clone it to the favorite tab. So here, just do the togglings and for the favorite tab, just call the previous named function to clone them all!
On a cloned element, you want to remove it from favorites and toggle the original element classes. See the code to get this twist I made! I redefined some variables in this case.
Notice there no more tempArray in use.
;)
var favoriteTab = $("#fav .spaces");
// Named function to load the favorites tab
function loadFav(){
// First, clear old favorites.
favoriteTab.empty();
// Look for filled hearts
var favCount = 0;
$(".tab-content").find("i.fa-heart").each(function(){
// Count them
favCount++;
// Clone its box
var favClone = $(this).closest(".box").clone();
// Change the id
favClone.attr("id", favClone.attr("id")+"_clone");
// Append to favorites
favoriteTab.append(favClone);
});
console.log("favCount: "+favCount);
localStorage.setItem("favAmount", favCount);
}
// Click handler
$('div.tab-pane').on('click', '.favorite', function(e) {
e.preventDefault();
// Elements we play with... Having significative variable names.
var heartLink = $(this);
var box = heartLink.parent('.box');
var thisID = box.attr("id");
var container = box.parent('.box-container');
if(thisID.split("_")[1] == "clone"){
console.log("You clicked a clone!");
// Remove that clone
box.remove();
// Use the original element for the rest of the function.
heartLink = $("#"+thisID.split("_")[0]).find("a.favorite");
box = heartLink.parent('.box');
thisID = box.attr("id");
}
//TOGGLE FONT AWESOME ON CLICK
heartLink.find('i').toggleClass('fa-heart fa-heart-o'); // .selected or not, you need those 2 classes to toggle.
box.toggleClass("selected not-selected"); // Toggle selected and not-selected classes
// Clone div
loadFav();
// Save this current toggle state
localStorage.setItem(box.attr("id"), heartLink.find("i").attr("class"));
console.log(heartLink.find("i").attr("class"));
});
// ON PAGE LOAD
// Append item if localstorage is detected
if (localStorage["favAmount"]>0) {
console.log("storage exist");
// Load heart's element states
$(".box").each(function(){
console.log( $(this).attr("id") );
console.log( localStorage.getItem($(this).attr("id")) );
if(localStorage.getItem($(this).attr("id")) != null){
$(this).find("i").removeClass().addClass( localStorage.getItem($(this).attr("id")) );
}
});
// Load favorites
loadFav();
}else{
console.log("no storage");
}
CodePen v6
How to add only selected class and remove other class which is selected before?
<html>
<select name="Button-Style" id="Button-Style" style="width:100%;">
<option value="Sun-Flower">Sun Flower</option>
<option value="orange-flat">orange-flat</option>
</select>
<script>
$(document).ready(function(){
$('#Button-Style').change(function(){
if($(this).val() == 'sun-flower'){
$("#$id>input").addClass('sun-flower-button');
}
else if($(this).val() == 'orange-flat'){
$("#" + id).addClass('orange-flat-button');
}
else{
}
});
});
</script>
</html>
I want to add only one class at a time.
You can do it like this with jquery.
$('.selected_check').change(function () {
if ($(this).is(":checked")) {
var x = $(this).closest('tr').prop('id');
var id = "#" + x;
$(id).removeClass('td_bgcolor');
$(id).addClass('highlight_row');
} else {
var y = $(this).closest('tr').prop('id');
var id = "#" + y;
$(id).removeClass('highlight_row');
$(id).addClass('td_bgcolor');
}
});
simply use removeClass and addClass cheers!!
Use removeClass() function in jQuery.
As for example;
HTML:
<div id="adiv" class="1st-class"></div>
Now jQuery;
$("#adiv").addClass("2nd-div"); // This 'll add 2nd-class with the div
$("#adiv").removeClass("1st-div"); //This 'll remove the 1st-class from the div.
Now if you want to remove all previous added class simply do;
$("#adiv").removeClass(); //removeClass without any argument removes all class
I'm having some difficulty understanding your question, but I think I get the gist of it.
Say you have the following HTML:
<div class="menu">
<div class="menu--option">Option 1</div>
<div class="menu--option">Option 2</div>
<div class="menu--option">Option 3</div>
</div>
Whenever someone clicks on an option, we want to add the class s-active to it, while making sure it is the only one with that class. You will want to do something like this:
// First, we listen to the click event.
$("menu--option").click(function () {
// When it fires, we select all of the menu options,
// and iterate over them, removing '.s-active' from it
// if the element has the class.
$("menu--option").each(function () {
$(this).removeClass("s-active");
});
// Finally, we add '.s-active' to the element that was clicked.
$(this).addClass("s-active");
}
Hopefully this was helpful!
You can code it in this way!
$('#Button-Style').change(function(){
$(this).removeClass();
if($(this).val()=="your_option_value"){
$(this).addClass("new_class");}
}
I am not sure to selection of element on which you are adding class but you can use removeClass() without supplying parameter to function to remove all previously applied class to item and then add your class as you are doing using addClass()
if($(this).val() == 'sun-flower'){
$("#$id>input").removeClass(); // Remove all classes .. although please check selector
$("#$id>input").addClass('sun-flower-button');
}
else if($(this).val() == 'orange-flat'){
$("#" + id).removeClass();
$("#" + id).addClass('orange-flat-button');
}
Also may I suggest passing class name directly from option values in select item. Then no need for extra if condition .
<select name="Button-Style" id="Button-Style" style="width:100%;">
<option value="Sun-Flower-button">Sun Flower</option>
<option value="orange-flat-button">orange-flat</option>
</select>
and in jquery
$('#Button-Style').change(function(){
var className = $(this).val();
$('#inputElement').removeClass();
$('#inputElement').addClass(className);
});
If you are trying to remove all previous classes and add a new one, you can use jQuery's toggleClass function.
I want to remove class of div id from other page anchor link.
firstPage.html
<div class="question show" id="a1">
Sample 1
</div>
<div class="question" id="a2">
Sample 2
</div>
list.html
$(function () {
$("a").click(function () {
$("#a2").addClass('question show');
});
});
</script>
</head>
<body>
Link 1
Link 2
</body>
I want to add class addClass('question show') to that div id which is clicked.
I tried here with Link1 for id=a1
But I'm failed to set class ('question show') help me to correct my code
Please check code here
http://plnkr.co/edit/fzdfjdrRbcWmir5wHcJW?p=preview
I'm taking a different approach. I'll not add the function to list.html. Let the page firstPage.html be called with the value. We will capture the anchor from firstPage.html.
Also, since your all divs have the class 'question'; I'm ignoring that class and targeting only 'show' class.
So, load this function with your firstPage.html:
$(document).ready(function(){
var call = $(location).attr('href').split('#');
var ancr = $.trim(call[1]);
if(ancr === undefined || ancr == ''){
// Anchor not set, do nothing
} else {
if (!$('#'+ancr).hasClass('show')) {
$('#'+ancr).addClass('show');
}
}
});
I also assume you don't have multiple divs with same ID (which generally should not be).
I hope this will do what you need.
I appreciate all the suggestions I've gotten so far-thank you!
I'll try to describe a bit better what I'm trying to do:
I want to switch a CSS class on the active (clicked on) tab item on a item (to make a highlight effect while its related content is showing).
The JS Fiddle http://jsfiddle.net/4YX5R/9/ from Vlad Nicula comes close to what I'm trying to achieve, however I can't get it to work in my code.
The tabs are linked to content which is shown on the page when the tab is clicked. This part is working fine. I just want to change the CSS style on the ContentLink items when its content is being shown.
I'd also like to keep the content for ContentLink1 visible when the page loads, as it is now in the code, and for ContentLink1 to have the CSS .infoTabActive class when the page loads. When the ContentLink tab is not clicked, it should have the .infoTab class.
This is what I have so far:
HTML:
<article class="grid-70 infoContainer">
<a class="infoTab" id="aTab" href="javascript:show('a')">ContentLink1</a>
<a class="infoTab" id="bTab" href="javascript:show('b')">ContentLink2</a>
<a class="infoTab" id="cTab" href="javascript:show('c')">ContentLink3</a>
<div id="a">
<p> Inhalt 1111111.</p></div>
<div id="b">
<p>Inhalt 222222222
</p></div>
<div id="c">
<p>Inhalt 33333333
<7p></div>
</article>
Javascript:
window.onload = function () {
document.getElementById("a").style.display = "block";
}
function show(i) {
document.getElementById('a').style.display ="none";
document.getElementById('b').style.display ="none";
document.getElementById('c').style.display ="none";
document.getElementById(i).style.display ="block";
}
basic CSS for tab styles I want to apply:
.infoTab {
text-decoration:none;
color:red;
}
.infoTabActive {
text-decoration:none;
color:yellow;
}
Any pointers would be appreciated!
You can switch the classes simply bu using class property on DOM element.
To replace the existing class use
document.getElementById("Element").className = "ClassName";
Similarly to add a new class to exisiting classes use
document.getElementById("Element").className += "ClassName";
Change show function to be like this:
function show(i) {
document.getElementById('a').style.display ="none";
document.getElementById('a').className ="";
document.getElementById('b').style.display ="none";
document.getElementById('b').className ="";
document.getElementById('c').style.display ="none";
document.getElementById('c').className ="";
document.getElementById(i).style.display ="block";
document.getElementById(i).className ="selected";
}
I changed a little bit your code to make it suits your needs.
First, change the onload part in the Fiddle, by no wrap.
Then, you need to hide each elements at start like this :
window.onload = function () {
var list = document.getElementsByClassName("hide");
for (var i = 0; i < list.length; i++) {
list[i].style.display = "none";
}
}
I added an hide class to achieve it. Your show function works well then.
I would do it like this:
add a class called .show which sets the element to display block.
then toggle the classname.
Here's a JSFiddle
And here's an example:
HTML
<article class="grid-70 infoContainer">
<a class="infoTab" id="aTab" href="javascript:show('a')">Werbetexte</a>
<a class="infoTab" id="bTab" href="javascript:show('b')">Lektorate</a>
<a class="infoTab" id="cTab" href="javascript:show('c')">Übersetzung</a>
<div class="box" id="a">
<div class="col1"> <p>Inhalt 1111111.</p></div>
</div>
<div class="box" id="b">
Inhalt 222222222
</div>
<div class="box" id="c">
Inhalt 33333333
</div>
</article>
JavaScript
window.onload = function () {
show('a');
}
function show(elm) {
// get a list of all the boxes with class name box
var shown = document.getElementsByClassName('box');
// loop through the boxes
for( var i=0; i<shown.length; i++ )
{
// set the classname to box (removing the 'show')
shown[i].className = 'box';
}
// change the classname to box show for the element that was clicked
document.getElementById( elm ).className = 'box show';
}
CSS
.box {
display:none;
}
.box.show {
display:block;
}
Simplest way I could think of is this : http://jsfiddle.net/4YX5R/9/
Basically you don't want to listen to each element. If you do that you will have issues with new tabs. If you listen to the parent element like in my example you can add new tabs without having to write any more javascript code.
<a class="infoTab" data-target='a' id="aTab">Werbetexte</a>
Each tab button has a data-target attribute that will describe the div to show as the tab content. Hiding and showing content will be done via css, not style - which is a recommended best practice -.
tabs.addEventListener("click", function ( ev ) {
var childTarget = ev.originalTarget || ev.toElement;
...
}
When a tab is clicked, we check to see which element was clicked from the event listener on the parent, and then get the data-target from it. We use this as a id selector to show the new tab. We also need a reference to the old tab that was active, so we can hide it.
The logic is not that complicated, and with this you can have any number of tabs. I would recommend jQuery for this, since the event delegation might not work in all browsers with the current code.
I hope this helps :)
I have the following div collection in my HTML. It's designed to dynamically replicate according to user interaction.
<div class="bill-item">
<!-- Section for a single item -->
<div class="bill-item-img">
<!-- Section for Item pic -->
</div>
<div class="bill-item-description">
<!-- Section for Item description and pricing -->
<div class="bill-item-name">
<p class="bill-item-name-left">Normal Cofee</p><p class="bill-item-name-right">170.00</p>
<div class="clear"></div>
</div>
<div class="bill-item-price">
<span>170.00 USD</span>
</div>
<div class="bill-item-amount">
<span>2</span>
</div>
</div>
<div class="bill-amount-selection">
<!-- Section where the increment & decrement of item amount goes -->
<a class="amount-increase" href="#"></a>
<a class="amount-decrease" href="#"></a>
</div>
</div>
This is the HTML Rendered image of the elements.
I've written the following script to increase the bill-item-amount span value.
$(".amount-increase").click(function(){
x+=1;
$(".bill-item-amount span").html(x);
});
$(".amount-decrease").click(function(){
if(!x<=0){
x-=1;
$(".bill-item-amount span").html(x);
}
});
This works great but, it updates the value of both the span elements. what I want is to catch the event of the clicked element (which I do now) and increase the span value of the respective span. How can I filter out which span to update using javascript.?
Something like $(this).parents('.bill-item').find('.bill-item-amount span') should select the right element.
Inside your callback this is assigned to the eventSource.
You should walk the dom tree from the clicked element up until you reach the .bill-item element and the go down to the .bill-item-amount span node
$(".amount-increase").click(function(){
var $span = $(this).parent().parent().find(".bill-item-amount span");
var x = $span.html();
x+=1;
$span.html(x);
});
$(".amount-decrease").click(function(){
var $span = $(this).parent().parent().find(".bill-item-amount span");
var x = $span.html();
if(!x<=0){
x-=1;
$span.html(x);
}
});
Hi dimal update your code:
$(".amount-increase").click(function(){
x+=1;
$(".bill-item-amount").html(x);
});
$(".amount-decrease").click(function(){
if(!x<=0){
x-=1;
$(".bill-item-amount").html(x);
}
});
dont add span inside the selector [ it changes entire span values]
$(".amount-increase").click(function(){
x+=1;
$("use ur increase span id here").html(x); //
});
$(".amount-decrease").click(function(){
if(!x<=0){
x-=1;
$("use ur decrease span id here").html(x);
}
});
Inside each function the selector $(".bill-item-amount span") will find all the <span> amounts in the document. You can walk the DOM to find the correct <span> using jQuery or plain JavaScript. You seem to be using jQuery functions so my answer also uses jQuery.
The following code combines the two actions into a single function that increases or decreases the amount based on the class name of the <a> clicked. I also added a return false so that the browser will not follow the href="#" on the anchor.
$('.bill-amount-selection').on('click', 'a', function(){
var change = this.className == 'amount-increase' ? 1 : -1
var $amount = $(this).closest('.bill-item').find('.bill-item-amount span')
var amount = parseInt($amount.html(), 10) + change
$amount.html(amount < 0 ? 0 : amount)
return false
});
The use of .on() means that jQuery v1.7+ is required. I can supply a compatible function with lower jQuery versions if necessary.