JQuery not removing active class - javascript

I'm trying to make my links slide down over the page when the mobile nav is clicked and the content to disappear so only the links are shown. I have got this basically working but the .displayNone class will not remove when I click the mobilenav again and I'm a bit dumfounded as to why.
$(document).ready(function() {
$('#hamburger').on('click', function(){
$('.links').slideToggle(200);
var status = $('.wrapper').hasClass('.displayNone');
if(status){ $('.wrapper').removeClass('.displayNone'); }
else { $('.wrapper').addClass('displayNone'); }
});
});
Bit of newbie to all this. Anything obvious that anyone can see wrong with this?

Use toggleClass(),
$('.wrapper').toggleClass('displayNone');
And, jQuery's xxxClass() functions expect the name of the class, not the selector, so leave off the . class selector.

When adding/removing classes, just use displayNone, not .displayNone (note the dot!).
Also there's a toggleClass() function which saves you from doing the status thing, which means you just need to do
$('.wrapper').toggleClass('displayNone');

your are doing bit wrong
var status = $('.wrapper').hasClass('.displayNone');
when you use hasClass, addClass or removeClass then you don't need to have '.' dot before class name.
so correct way is
var status = $('.wrapper').hasClass('displayNone');
your code after correction
$(document).ready(function() {
$('#hamburger').on('click', function() {
$('.links').slideToggle(200);
var status = $('.wrapper').hasClass('displayNone');
if (status) {
$('.wrapper').removeClass('displayNone');
} else {
$('.wrapper').addClass('displayNone');
}
});
});

You can use :
$('.wrapper').toggleClass("displayNone");
Final code :
$(document).ready(function(){
$('#hamburger').on('click', function(){
$('.links').slideToggle(200);
$('.wrapper').toggleClass("displayNone");
})
})

Related

How change the css with the checkbox with different names?

Currently, I have multiple checkbox inputs with different names(checkit, checktype, checklog) assigned to the inputs.
What I want to do is to have each checkbox to change the color of the background when checked.
However, I dont know how I can assign each one of the checkbox to do some tasks without duplicating the following code ?If possible some examples or tips will be great! I would love to hear from you .
Should I remove name="checkit" if I want to make all the inputs do the same thing? What if I want them to do some slightly different things?
$('input[name="checkit"]').change(function () {
if ($(this).prop('checked')) {
$(this).parent().parent().addClass('alterBackground');
} else {
$(this).parent().parent().removeClass('alterBackground');
}
});
Add the following by , or give some class name to it
$('input[name="checkit"], input[name="checktype"], input[name="checklog"]').change(function () {
if ($(this).prop('checked')) {
$(this).parent().parent().addClass('alterBackground');
} else {
$(this).parent().parent().removeClass('alterBackground');
}
});
Don't use the name atrribute in jQuery and add a common class to each checkbox for a common functionality and access it with class selector in jQuery as shown below.
If you want to do something different with different checkboxes apart from this, then you can add more jQuery code for that specific input tag. It will not affect this code.
$('input.someClass').change(function () {
if ($(this).prop('checked')) {
$(this).parent().parent().addClass('alterBackground');
} else {
$(this).parent().parent().removeClass('alterBackground');
}
});
You can remove the name part from the selector and add selector for input[type='radio']. And if you want to add a bit different logic (I think you mean different classes), you can get the name of the current checked checkbox and use it to make your logic. Something like this
$('input[type="radio"]').change(function () {
var checkboxName = $(this).prop('name');
// if(checkboxName === .....)
});
Updated according to the comment
$('input[name="checkit"], input[name="checktype"], input[name="checklog"]').change(function () {
var checkboxName = $(this).prop('name');
// .............
});
$('input[type="checkbox"]').change(function () {
if ($(this).prop('checked')) {
$(this).parent().parent().addClass('alterBackground');
} else {
$(this).parent().parent().removeClass('alterBackground');
}
});
Use
$('input[type="checkbox"]')
instead of
$('input[name="checkit"]')

Checking Id of clicked element

I have several images with the same class and would like to set up a click function that changes the text in some elements based on which image is clicked.
My if statement is not working, I'm not entirely sure why because I've used this method before, or so I thought.
$('.gallery_image').click(function(e) {
var t = $(this);
if(t.id == 'csf') {
console.log('It works!');
}
});
JSFIDDLE
Use t.attr('id') instead of t.id
More about .attr()
An alternate solution is using classes instead of id's. Call the click function on the class they share then use a second class to distinguish them with the hasClass function:
<div id="csf" class="gallery_image csf">csf</div>
<div id="csi" class="gallery_image csi">csi</div>
$('.gallery_image').click(function(e) {
var t = $(this);
if(t.hasClass('csf')) {
alert("It works!");
}
else if(t.hasClass('csi')) {
alert("So does this!");
}
});

click event not working when changing id or class

I'm starting with jquery, and have an issue here:
http://jsfiddle.net/8guzD/
$('#test.off').click(function(){
$(this).removeClass('off').addClass('on');
});
$('#test.on').click(function(){
$(this).removeClass('on').addClass('off');
alert('ok');
});
the first part of the code goes well, the class is apply, but when I attach an event in this element with its new class it won't work.
Can someone explain me what is the problem exactly?
I tried with javascript,
http://jsfiddle.net/R5NRz/
var element = document.getElementById('test');
element.addEventListener('click', function() {
this.id ='test2';
alert("ok");
}, false);
var element2 = document.getElementById('test2');
element2.addEventListener('click', function() {
alert("ok2");
}, false);
and it didn't really help me, having the same issue
try
$(document).on("click",'#test.on',function(){
$(this).removeClass('off').addClass('on');
alert('ok');
});
$(document).on("click",'#test.off',function(){
$(this).removeClass('off').addClass('on');
alert('ok passs');
});
Demo
In your jQuery example you are binding to DOM elements that exist at that time. That is why you see the first fire but not the second. It is not a match for your '#test.on' selector when the code is run. What you want to do instead is use delegation:
$('#test').on('click',function() {
var ele = $(this);
if (ele.hasClass('on')) {
ele.removeClass('on').addClass('off');
} else {
ele.removeClass('off').addClass('on');
}
});
This assumes that you are doing more than just toggling classes. If you want simply toggle classes then an easier solution is to pick one as the default and use the other as a flag. For example, .on is on but without .on it's off. Then you can just use toggle:
$('#test').on('click', function() {
$(this).toggleClass('on');
});
$("#test.on")
Doesn't bind to anything. Try this:
$('#test').click(function() {
if($(this)).hasClass('off') $(this).removeClass('off').addClass('on');
else $(this).removeClass('on').addClass('off');
});
You might consider using an 'active' class instead and just toggling that, instead of have two separate on/off classes. Then you can write:
$("#test").click(function() {
$(this).toggleClass('active');
});

Jquery/Javascript Add class if X class is not exist

I am new here, sorry if I do some mistake with this question.
I have a HTML code.
hit me
with this function i can add class two in class one
$(document).ready(function () {
$('a#foo').click(function(){
$('.one').toggleClass('two');
});
});
but how if I want to add class two if class two is not exist and do other function if class two is exist?
maybe like this,
hit me
i klik hit me and jquery is add class two,
hit me
but when I klick hit me again, class two is not removed and because class is exist, i create other function based on class two is exist.
lets say like this,
i klik hit me
hit me
<div id="blah" class=""*>lorem</div>
then
hit me
<div id="blah" class=""*>lorem</div>
and klik hit me again.
hit me
<div id="foo" class="blah2">lorem</div>
can you give me code or google suggest keyword or link, because I confused what i must search first.
thanks for adv,
sorry for my Grammer, i cant speak/write English well, if any wrong grammer or language please correct me.
Using the hasClass() method and you're examples:
$(document).ready(function () {
$('a#foo').click(function(){
if ($(this).hasClass('two')) {
$('#blah').addClass('blah2');
} else {
$(this).addClass('two');
}
});
});
Use jQuery hasClass method .
$(document).ready(function () {
$('a#foo').click(function(){
if ($(this).hasClass('two')) {
doSomething();
} else {
$('.one').addClass('two');
}
});
});
i'm a little confused as to what exactly you want to do, but I think you need to look into .hasClass() for starters.
$(document).ready(function () {
$('a#foo').click(function(){
if ($('.one').hasClass('two')) {
// do stuff you want to do if element already has class "two"
}
else {
// do stuff if it doesnt already have class "two"
}
});
});
I am guessing at your exact needs, but I hope that my assumptions weren't too far off base.
Given HTML like this:
hit me
<div id="change" class="blah1"></div>
And JS Like this:
$(document).ready(function () {
$('a#foo').click(function(e){
e.preventDefault();
var changeDiv = $('#change');
if ($(this).hasClass('two')) {
changeDiv.addClass('blah2').removeClass('blah1');
changeDiv.html('<p>Blah 2</p>');
} else {
changeDiv.addClass('blah1').removeClass('blah2');
changeDiv.html('<p>Blah 1</p>');
}
$('.one').toggleClass('two');
});
});
You will be able to toggle your link's class and change or update another div based on the class of your link when clicked.
You can see this code working at http://jsfiddle.net/PTdLQ/4/
Another way to look at this is to check if the given class exists in the dom. Therefore, one can use the following:
$(document).ready(function () {
$('a#foo').click(function(){
if ($('.two').length) {
//there is a class two
SomeFunction();
} else {
//there is no class two
SomeOtherFunction();
}
});
});
Hope I typed it right
Use this code:
<script>
$(document).ready(function () {
if(!$('#mydiv').hasClass('myclass')) {
$('#mydiv').addClass('myclass');
}
});
</script>

A smart toggle class in jQuery

I am trying to implement a script to set different class name on a specific element…
Let's suppose the dom looks like this:
<body class='pre-existing-class-name'>
If I make
smartToogle('body', 'new-class');
// the dom should look like this
// <body class='pre-existing-class-name new-class'>
smartToogle('body', 'new-class-2');
// the dom should look like this
// <body class='pre-existing-class-name new-class-2'>
I did the following code but it does not work:
var smartToogle = function (element, newClassName) {
var oldClassName;
var $element = $(element);
$element.addClass(newClassName);
if (oldClassName !== newClassName) {
$element.removeClass(oldClassName);
}
oldClassName = newClassName;
};
Requirements:
1) I am using query
2) I would like to pass just one class name, the new one.
Solution:
The following code works but I do not like it because it uses global variable.
Any hint to fix it?
function myToggle(newClassName) {
if (window.oldClassName) {
$('body').toggleClass(window.oldClassName);
}
window.oldClassName = newClassName;
$('body').toggleClass(newClassName);
}
You can use data attribute for the element, that is accessible using
$(element).data(attrib_name)
Just a small change is required in your method
function myToggle(newClassName) {
if (window.oldClassName) {
$('body').toggleClass(window.oldClassName);
}
window.oldClassName = newClassName;
$('body').toggleClass(newClassName);
}
can be replaced with
function myToggle(element, newClassName) {
if ($(element).data('oldClassName')) {
$(element).toggleClass($(element).data('oldClassName'));
}
$(element).data('oldClassName', newClassName)
$(element).toggleClass(newClassName);
}
Hope this solves it for you.
Update:
There is one thing you need to understand.
If you want two different behaviors you don't need 2 different classes for the change in behavior.
One is enough, because you can change the behavior based on weither the class is on or off.
Let's say I want my element to have a red hover event in one way.
And want it to have a blue hover event the other way with CSS.
Then this is the way to go:
$('#toggle').click(function(){
$('.normal').each(function(){
$(this).toggleClass('active');
});
});
JSFiddle Demo
Here we use a button to toggle all the divs and change their CSS behavior, looks easy now right?
However if you need to toggle Javascript/jQuery events as well this won't do. In that case you will need to use 3 other methods to manage this; .on(), .off(), and .hasClass().
$('#toggle').click(function(){
$('.normal').each(function(){
if($(this).hasClass('active')){
$(this).off('click');
} else {
$(this).on('click', function(){
alert('You are clicking on an active div.');
});
}
$(this).toggleClass('active');
});
});
JSFiddle Demo 2
As you can see we have added an if statement. If the element has the .active class we turn .off() the .click(). And if there isn't an active class we turn the .click() .on(). Under the if statement we always toggle the .active class. So this doesn't have to be placed inside the if statement.
I hope this clears everything up for you, good luck!
Old Answer:
It is better to use .toggleClass() here.
Use a first class on the element for the default properties and a second like .active for example for the interaction.
Also, using a .on('click', function(){}) bind will make you able to add interaction that will be bound instantly once the element is toggled.
Here's a fiddle: http://jsfiddle.net/NCwmF/2/
I little jQuery plugin for that. Removes the current smart class (if any) and adds the new smart class. If called without parameter className the current smart class gets only removed.
$.fn.smartToggle = function (className) {
var dataId = 'smartToggle';
return this.each(function () {
var $el = $(this);
$el
.removeClass($el.data(dataId) || '')
.addClass(className)
.data(dataId, className);
});
};
​use it like every other jQuery method:
$('body').smartToggle('myClass');
NEW, SIMPLER ANSWER
Works similar to before, with 2 additions: 1.) works if there is no class initially and 2.) works if other functions change the elements class in between calls. I also changed the function name so it doesn't interfere with jQuerys native toggleClass.
$.fn.fancyToggleClass = function(new_class) {
return this.each(function() {
// get the last class this function added (if exists) or false (if not)
var $this = $(this),
toggled_class = $this.data('toggled-class') || false;
// if we dont have an original class, then set it based on current class
if (toggled_class) {
$this.removeClass(toggled_class);
}
// add new class and store as data,
// which we check for next time function is called
$this.addClass(new_class).data('toggled-class', new_class);
// alert the class, just as a check to make sure everything worked!
// remove this for production, or switch to console.log
alert('element class: ' + $this.attr('class'));
});
}
updated fiddle: http://jsfiddle.net/facultymatt/xSvFC/3/
OLD ANSWER
I would suggest storing the original class in the elements data attribute. Then, your function can check if this data is set, and if so clear the elements class adding the original class from the elements data and also the new class you passed in the function.
If data is not set, the function will store the current class as data the first time it runs.
Check out this fiddle for a working example with comments: http://jsfiddle.net/facultymatt/xSvFC/
here is the code. It's a jquery function so it can be called on any element (and is chainable too!)
$.fn.toggleClass = function(new_class) {
return this.each(function() {
// cache selector for this
$this = $(this);
// get original class (if exists) or false (if not)
var original_class = $this.data('original-class') || false;
// if we dont have an original class, then set it based on current class
if (!original_class) {
original_class = $this.attr('class');
$this.data('original-class', original_class);
// we do have an original class, so we know user is now trying to add class
// here we clear the class, add the original class, and add the new class
} else {
// assign the original class, and new class,
// and a space to keep the classes from becoming one
$this.attr('class', original_class + ' ' + new_class);
}
// alert the class, just as a check to make sure everything worked!
// remove this for production, or switch to console.log
alert('element class: ' + $this.attr('class'));
});
}
Hope this helps!
To avoid a global variable you can use data attribute as #ankur writes. Here is a working solution for your problem:
function myToggle(element, newClassName) {
if (!$(element).data('baseclassname')) {
$(element).data('baseclassname', $(element).attr('class'));
}
$(element)
.attr('class', $(element).data('baseclassname'))
.addClass(newClassName);
}
Does this do your job?
var smartToogle = function (element, preExistingClassName, newClassName) {
$(element)[0].className = preExistingClassName + ' ' + newClassName;
};
Just use hasClass. But you'll have to tell the function what both classes are:
function smartToggle(element, class1, class2) {
var $element = $(element);
if ($element.hasClass(class1)) {
$element.removeClass(class1);
$element.addClass(class2);
}
else {
$element.removeClass(class2);
$element.addClass(class1);
}
}
$(function(){
var smartToggle = function (element, newClassName) {
var elementClasses = element.attr('class');
element.addClass(newClassName);
// check if there is more than one class on the element
if(elementClasses .indexOf(' ') >= 0){
var oldClassNames = elementClasses.split(" ");
if (oldClassNames[oldClassNames.length - 1] !== newClassName) {
element.removeClass(oldClassNames[oldClassNames.length - 1]);
}
}
};
smartToggle($('.test'), 'newclass');
smartToggle($('.test'), 'newclass2');
});
Demo - http://jsfiddle.net/Q9A8N/ (look at the console to see what it is doing on each pass)
That should do what you want but as #T.J. Crowder said it is rather fragile and assumes that the class you want to remove is the last one on the element.
As an answer to your question, I would go with ankur's answer
As a follow-up to Sem's answer, regarding the handling of jQuery events :
you can use the on function to handle any jquery event from a parent node, based on a live filter :
function myToggle(element, newClassName) {
if ($(element).data('oldClassName')) {
$(element).toggleClass($(element).data('oldClassName'));
}
$(element).data('oldClassName', newClassName);
$(element).toggleClass(newClassName);
}
//event delegation : 'on' is called on the $('.divContainer') node, but we handle
//clicks on '.divItm' items, depending on their current class
$('.divContainer')
.on('click', '.divItm.plain', function(){ myToggle( this, 'red' ); })
.on('click', '.divItm.red', function(){ myToggle( this, 'blue' ); })
.on('click', '.divItm.blue', function(){ myToggle( this, 'plain' ); });
//initialize each item with the 'plain' class
myToggle( $('.divItm'), 'plain' );
Here is the jsFiddle.
You will note that the function called each time you click on an item depends on its "live" class, and that you don't need to manually enable/disable click handlers each time an item changes class.
You can learn more details from the documentation page.
var smartToogle = function (element, newClass) {
var $element = $(element),
currentClass = $element.data('toggle-class');
if (currentClass != newClass) $element.data('toggle-class',newClass).removeClass(currentClass || '');
$element.toggleClass(newClass);
};
or the other variant:
$.fn.smartToogle = function (newClass) {
currentClass = this.data('toggle-class');
if (currentClass != newClass) this.data('toggle-class',newClass).removeClass(currentClass || '');
this.toggleClass(newClass);
};
In this implementation you'll have to keep the a reference to this instance of fancytoggle.
var fancytoggle = function(el, oldClass){
// create a function scope so we'll have a reference to oldClass
return function(newClass) {
// toggle the old class and the new class
$(el).toggleClass(oldClass+ ' ' + newClass);
// update the new class to be the old class
oldClass = newClass;
};
};
for your example the code would look something like.
var bodytoggle = fancytoggle('body', 'pre-existing-class-name');
bodytoggle('new-class');
// 'new-class' replaces 'pre-existing-class-name'
bodytoggle('new-class-2');
// 'new-class-2' replaces 'new-class'
to see it in action refer to http://jsfiddle.net/aaf2L/6/

Categories

Resources