Jquery class checking and changing - javascript

I posted a question up yesterday that asked for some help on an image switching script I had written, thank you to all that helped me. I've extended the script and have run into a problem that I can't for the life of me spot where the problem is.
HTML:
<div id="feature-image">
<h1><span>A random heading</span></h1>
</div>
<div id="feature-links">
<a class="a1" href="#">1</a>
<a class="a2" href="#">2</a>
<a class="a3" href="#">3</a>
</div>
JS + Jquery:
$(function(){
$('#feature-links a').click(function() {
if ($(this).hasClass('a-active')) {
return false;
} else {
var image = $(this).attr('class');
switchToImg(image, function() {
$('#feature-links a .a-active').removeClass('a-active');
$('#feature-links .' + image).addClass('a-active');
});
}
});
function switchToImg(image){
$('#feature-image').fadeOut('300', function(){
$('#feature-image').css('background-image','url(images/main_' + image + '.jpg)');
$('#feature-image').fadeIn('300');
});
};
In the script I check for a click on an <a> tag, each <a> tag has a class of (a1, a2, a3 etc.). Also, the active <a> has a class of 'a-active'.
I'm attempting to check if a-active is set with this:
if ($(this).hasClass('a-active')) {
return false;
}
and cut the script there so that it doesn't fade in and out the same image. However, the image continues to fade in and out despite my return false on checking for the class a-active and returning false. I am sure the problem is in the section where I am using .addClass and .removeClass but my knowledge of Javascript and Jquery is to flaky for me to properly debug this.
Could someone cast a critical eye over this please?
Thanks in advance.

You have incorrectly passed an anonymous function to your switchToImg() function, which doesn't accept one.
Instead, try the following JS:
$(function() {
$('#feature-links a').click(function() {
if ($(this).hasClass('a-active')) {
return false;
} else {
var image = $(this).attr('class');
switchToImg(image);
}
});
function switchToImg(image) {
$('#feature-image').fadeOut('300', function() {
$('#feature-image').css('background-image', 'url(images/main_' + image + '.jpg)');
$('#feature-image').fadeIn('300');
});
$('#feature-links a.a-active').removeClass('a-active');
$('#feature-links .' + image).addClass('a-active');
};
});
Tested in jsFiddle.
EDIT: I removed the call to .stop(), it wasn't necessary and introduced a bug.

Try changing $('#feature-links a .a-active') to $('#feature-links a.a-active').
Space between a and .a-active means you're trying to match descendants of <a> with class a-active.

You can use :not selector to filter out active class.
$('#feature-links a:not(.a-active)')

Related

How can I combine .toggleClass() with .appendTo()?

I append a new class to a HTML container. How can I toggle this on/off by clicking on the menu button?
And is it even "best practice" to write more complex HTML code in JavaScript or would you prefer another method for this? Because I plan to do this for some more containers. Thank you!
$(document).ready(function() {
$( "a.header-login" ).click(function() {
$("<div class='sub-menu'>" +
"<h2>Hi x!</h2>"+
"<a class='item' href='#'>Logout</a>"+
"</div>")
.appendTo("header .header-r");
})
});
I want to accomplish that another click on "a.header-login" deletes the container ".sub-menu". Now, it is always generated when you click "a.header-login"
In this case you need to add a condition to check whether or not the element already exists. If it doesn't create it, if it does remove it.
jQuery(function() {
$('a.header-login').click(function() {
var $target = $('header .header-r .sub-menu');
if ($target.length === 0) {
$('<div class="sub-menu"><h2>Hi x!</h2><a class="item" href="#">Logout</a></div>').appendTo('header .header-r');
} else {
$target.remove();
}
})
});
That being said, you can make this much simpler logic if you always include the .sub-menu in the HTML of your page but hide it with CSS by default. In that case your jQuery would become a simple call to toggle():
jQuery(function() {
$('a.header-login').click(function() {
$('header .header-r .sub-menu').toggle();
})
});

JQuery not removing active class

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

javascript toggle visibility and add function preventDefault

i´m trying to display popup-divs within a site and it works quite well, except for one thing –
i want to prevent the Default behavior of refreshing the site. I´m new to javascript and i honestly don´t know how to add the function (i already found the right one, i think...).
<script type="text/javascript">
function toggleVisibility(selectedPopup) {
var popvar = document.getElementsByClassName('popup');
for(var i=0; i<popvar.length; i++) {
if(popvar[i].id == selectedPopup) {
popvar[i].style.visibility = 'visible';
} else {
popvar[i].style.visibility = 'hidden';
}
}
}
It works like i wanted it to work – it displays the selected DIV, hides the other and vice versa.
Still, i want to prevent the site from jumping to the top. So i added this snippet:
$(function() {
$("#").click(function(event){
event.preventDefault()
});
});
The responding html is this:
<a href="#" onclick="toggleVisibility('pop01');">
and this
<div id="pop01" class="popup">
<img src="assets/img/01/01_02_pop_01.png"></img>
</div>
How can i include the second javascript snippet into the first one?
Many thanks in advance...
You should just be able to pass event into your function.
The HTML
<a href="#" onclick="toggleVisibility(event, 'pop01');">
The Javascript (partial)
function toggleVisibility(event, selectedPopup) {
event.preventDefault();
var popvar = document.getElementsByClassName('popup');
// etc...
}
I believe that should do it!
JSFiddle Example: http://jsfiddle.net/c4LXf/
As an alternative you can just remove the # and replace with javascript:;
<a href="javascript:;" onclick="toggleVisibility('pop01');">
Or remove the onclick and just use the href:
<a href="javascript:toggleVisibility('pop01');">
Instead of
$(function() {
$("#").click(function(event){
event.preventDefault()
});
try
$(function() {
$("#").click(function(event){
return false;
});
You can just use following:
<a href="#" onclick="return toggleVisibility('pop01');">
If you add a return false in your function:
function toggleVisibility(selectedPopup) {
// your code ...
return false;
}
Or, Change your link like:
<a href="javascript:toggleVisibility('pop01');">

Attempting to loop and print an element in jQuery

I am attempting to loop through a dynamic element and then print it with jquery,
Heres the code i use
$('.recipe-steps #addNewStep').on('click', function () {
var s = $('.recipe-steps .step').size() + 1;
$('<div class="step pure-u-1-1"><textarea id="step" name="step_detail[]" class="pure-u-1" placeholder="Step ' + s + '"></textarea>×</div>').appendTo($('.recipe-steps .steps'));
return false;
});
$(document).on('click', '.step .remove', function () {
$(this).parents('.step').remove();
return false;
});
however its only printing out the first element and not the preceding ones. I have created a fiddle can anyone see why?
http://jsfiddle.net/drk8X/
I wasn't able to come up with the perfect solution (will have a look later) but I have redesigned the function to work to an extent.
$("body").on('input propertychange', function () {
var outputme="";
$('textarea').each(function (index) {
outputme+='<br>'+(index+1) + '. ' + $(this).val();
});
$('#lp-step').html('<h3>Method</h3>'+outputme);
});
This will update the "preview" on change of the text area, use CSS Selectors to narrow down the scope, but id reccomend you looking at your HTML and try and simplify it a bit more.
http://jsfiddle.net/drk8X/2/

adding specific class to element on click jquery

I'm having trouble with a simple nav bar that uses jQuery to add and remove a specific class when a certain page is active. I want a class to append to my aLink class depending on which ID is click. If I click on #aboutLink I want .linkActive to be added, but if I click on #sasLink I want .link2Active to be added. The tutorials I've looked at all have a single class being added, but since both my classes are different I need a specific one to be added depending on which ID is click.
HTML:
<div id="mainNav">
<ul id="nav">
<a id="mainLogo" href="/"><li></li></a>
<a id="aboutLink" class="aLink" href="/"><li></li></a>
<a id="sasLink" class="aLink" href="/savings-and-support"><li></li></a>
<a id="external" href="/"><li></li></a>
</ul>
</div><!--/#mainNav-->
I know my jQuery doesn't make sense, but it's all I could come up with. Logically I get it, but I'm lost on the syntax.
jQuery:
$(function () {
$(".aLink").click(function () {
if ($(this) == $("#aboutLink")
$(this).addClass('activeLink');
else $(this).addClass('active2Link');
});
});
Thanks for any input or direction.
var idToClass = {
'aboutLink' : 'linkActive',
'sasLink' : 'link2Active'
}
$('#nav a').click(function(){
e.preventDefault();
$(this).addClass(idToClass[this.id]);
});
JS Fiddle demo.
You could, instead, use toggleClass() to allow for those classes to be removed by a second click:
var idToClass = {
'aboutLink' : 'linkActive',
'sasLink' : 'link2Active'
}
$('#nav a').click(function(e){
e.preventDefault();
$(this).toggleClass(idToClass[this.id]);
});
JS Fiddle demo.
Edited in response to question, from the OP, in comments, below:
How would I remove the class so that both links don't appear to be active at the same time?
There's a few ways, but because you're adding different class-names to denote the 'active' state, they're a little inefficient. The first approach is to use a brute-force method, effectively looking for all a elements that have a class attribute and setting that attribute to the empty string, and then adding the linkActive/link2Active class-name to the clicked-on a element:
$('#nav a').click(function(e){
e.preventDefault();
var self = $(this);
self.closest('ul').find('a[class]').attr('class', '');
self.toggleClass(idToClass[this.id]);
});
JS Fiddle demo.
The alternative is to remove the specific classes from the elements who have their id listed in the idToClass object. This is, however, somewhat expensive in that it needs to iterate over the object, retrieving the id, finding the element with that id and then removing a class-name:
$('#nav a').click(function(e){
e.preventDefault();
for (var id in idToClass) {
if (idToClass.hasOwnProperty(id)){
$('#' + id).removeClass(idToClass[id]);
}
}
$(this).addClass(idToClass[this.id]);
});
JS Fiddle demo.
If, of course, you use a common class-name then it all becomes much easier:
$('#nav a').click(function (e) {
e.preventDefault();
var self = $(this);
self.closest('ul')
.find('.commonActiveClassName')
.removeClass('commonActiveClassName');
self.addClass('commonActiveClassName');
});
JS Fiddle demo.
References:
addClass().
closest().
event.preventDefault().
find().
removeClass().
toggleClass().
Since you already have ID tags to easily reference... I think you want something more like this?
$(function () {
$("#aboutLink").click(function () {
$(this).addClass('activeLink');
});
$("#sasLink").click(function () {
$(this).addClass('active2Link');
});
});
Try using this instead:
$(function () {
$(".aLink").click(function () {
var currentId = this.id;
if ( currentId == "aboutLink"){
$(this).addClass('activeLink');
else if( currentId == "sasLink") {
$(this).addClass('active2Link');
}
});
});

Categories

Resources