Don't execute the function when div has active class - javascript

I am trying to build basic animation of two divs with jQuery .toggle() function.
The main concept is to toggle the visibility of two additional divs with map and contact form.
I made everything working as I wanted but noticed a bug.
Here is the link to the demo on Codepen -- Link
To see the bug just hit 'Location' then 'Get in touch' and again
'Location'.
I think that it could be fixed with simple if else function, but I can't come up with the right solution since I don't know JS that much.
Anybody, help me, please.
Thanks in advance!

How about something like this. Basically just keeping track of whether the form and map are showing, and only doing the animation when necessary.
$(document).ready(function() {
// toggle map visibility
$("#toggle-map").click(function() {
$(".target-map").toggle('left');
});
// toggle contact form visibility
$("#toggle-form").click(function() {
$(".target-form").toggle('left');
});
var showingMap = false
var showingForm = false
function animate() {
var changeInLeft = !showingMap && !showingForm ? "0px" : "-245px"
$(".left-part").stop().animate({ left: changeInLeft }, 100);
}
// hide one on click
$(document).on("click", "#toggle-map", function(event) {
$(".target-form").hide();
event.preventDefault();
if (showingForm) showingForm = !showingForm;
showingMap = !showingMap;
animate();
});
$(document).on("click", "#toggle-form", function(event) {
$(".target-map").hide();
event.preventDefault();
showingForm = !showingForm;
if (showingMap) showingMap = !showingMap;
animate();
});
});

Related

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

Why is jquery toggle not working?

I simply want to have a variable toggle between true and false and have the text on the button clicked to change as well. Here is my Jquery:
$("button").toggle(
function () {
$(this).text("Click to change to paint brush");
var erasing = true;
},
function () {
$(this).text("Click to change to eraser");
var erasing = false;
}
);
This looks 100% sound to me, but in my jsfiddle you will see that it is toggling the existence of the button before I can even click it! Why is this happening and how can I fix it?
This version of toggle has been deprecated (1.8) and removed (1.9). Now you need to handle it in button click itself.
Somthing like this:
var erasing = false;
$("button").click(function () {
erasing = !erasing;
$(this).text(function (_, curText) {
return curText == "Click to change to paint brush" ? "Click to change to eraser" : "Click to change to paint brush" ;
});
console.log(erasing);
});
Fiddle
Plus if you want to preserve the value of the variable just define them out of the click event scope, so that it is more global to be accessed outside.
See
.toggle
.text(func) syntax
Deprecated toggle
Thank you all for explaining how toggle is out of date...so that is all I needed and then I solved my problem with a simple if statement:
var erasing = false;
var i = 0
$("button").click(function () {
if(i%2==0){
$(this).text("Click to change to paint brush");
erasing = true;
}
else{
$(this).text("Click to change to eraser");
erasing = false;
};
i += 1
});
jsfiddle
As PSL said, the toggle you're looking for is gone and lost. if you want a click and hold solution (as your title suggests), you could look at using mouseup and mousedown.
var erasing;
$("button").on({
"mousedown": function () {
$(this).text("Click to change to paint brush");
erasing = true;
},
"mouseup mouseleave": function () {
$(this).text("Click to change to eraser");
erasing = false;
}
});
Demo : http://jsfiddle.net/hungerpain/ymeYv/6/

Issue with using one button to open/close in JQuery

Hey guys I am trying to make a button that will open and close based on if it is clicked the first time - it opens, if the second time - it closes and resets.
Here is my code I have so far - it only opens and wont close:
var val;
$(".confirmed").click(function(){
if (val == 1){
hide();
}
val = 1;
$(".confirmedtable").show();
$(".searchconfirmed").show();
});
function hide(){
$(".confirmedtable").hide();
$(".searchconfirmed").hide();
val = 0;
}
Thanks
You can just use the toggle() function in jquery to do this. See: http://api.jquery.com/toggle/
$('#button').click(function() {
$('#div_to_show_hide').toggle('slow', function() {
// Animation complete.
});
});
The toggle will show an element if it's currently hidden, and hide an element if it's currently shown.
$(".confirmed").click(function(){
$(".confirmedtable, .searchconfirmed").toggle();
});
FIDDLE
As an alternative to the toggle() based answers:
$('.confirmed').click(function(){
$('.confirmedtable, .searchconfirmed')[$('.confirmedtable').is(':visible') ? 'hide' : 'show']();
});
JS Fiddle demo.
It is, though, at best merely an alternative; the toggle() approach is more concise.

attach an event to the body when ul is visible, then remove it when invisible

I have a <ul> that when clicked, toggles the visibility of another <ul>. How can I attach an event to the body of the page when the <ul>s are revealed so that the body will hide the <ul>.
I am new to writing these sorts things which bubble, and I cannot figure out why what I have done so far seems to work intermittently. When clicked several times, it fails to add the class open when the secondary <ul> is opened.
And of course, there may be an entirely better way to do this.
$(document).on('click', '.dd_deploy', function (e) {
var ul = $(this).children('ul');
var height = ul.css('height');
var width = ul.css('width');
ul.css('top', "-" + height);
ul.fadeToggle(50, function () {
//add open class depending on what's toggled to
if (ul.hasClass('open')) {
ul.removeClass('open');
} else {
ul.addClass('open');
}
//attach click event to the body to hide the ul when
//body is clickd
$(document).on('click.ddClick', ('*'), function (e) {
e.stopPropagation();
//if (ul.hasClass('open')) {
ul.hide();
ul.removeClass('open')
$(document).off('click.ddClick');
// }
});
});
});​
http://jsfiddle.net/JYVwR/
I'd suggest not binding a click event in a click event, even if you are unbinding it. Instead, i would do it this way:
http://jsfiddle.net/JYVwR/2/
$(document).on('click', function (e) {
if ( $(e.target).is(".dd_deploy") ) {
var ul = $(e.target).children('ul');
var height = ul.css('height');
var width = ul.css('width');
ul.css('top', "-" + height);
ul.fadeToggle(50, function () {
//add open class depending on what's toggled to
if (ul.hasClass('open')) {
ul.removeClass('open');
} else {
ul.addClass('open');
}
});
}
else {
$('.dd_deploy').children('ul:visible').fadeOut(50,function(){
$(this).removeClass("open");
})
}
});​
If you need to further prevent clicking on the opened menu from closing the menu, add an else if that tests for children of that menu.
You dont' really need all that code. All you need is jquery's toggle class to accomplish what you want. simple code like one below should work.
Example Code
$(document).ready(function() {
$('ul.dd_deploy').click(function(){
$('ul.dd').toggle();
});
});​​​​
Firstly, you are defining a document.on function within a document.on function which is fundamentally wrong, you just need to check it once and execute the function once the document is ready.
Secondly why do you want to bind an event to body.click ? it's not really a good idea.
Suggestion
I think you should also look at the hover function which might be useful to you in this case.
Working Fiddles
JSfiddle with click function
JSfiddle with hover function

Prevent click event in jQuery triggering multiple times

I have created a jQuery content switcher. Generally, it works fine, but there is one problem with it. If you click the links on the side multiple times, multiple pieces of content sometimes become visible.
The problem most likely lies somewhere within the click event. Here is the code:
$('#tab-list li a').click(
function() {
var targetTab = $(this).attr('href');
if ($(targetTab).is(':hidden')) {
$('#tab-list li').removeClass('selected');
var targetTabLink = $(this).parents('li').eq(0);
$(targetTabLink).addClass('selected');
$('.tab:visible').fadeOut('slow',
function() {
$(targetTab).fadeIn('slow');
}
);
}
return false;
}
);
I have tried adding a lock to the transition so that further clicks are ignored as the transition is happening, but to no avail. I have also tried to prevent the transition from being triggered if something is already animating, using the following:
if ($(':animated')) {
// Don't do anything
}
else {
// Do transition
}
But it seems to always think things are being animated. Any ideas how I can prevent the animation being triggered multiple times?
One idea would be to remove the click event at the start of your function, and then add the click event back in when your animation has finished, so clicks during the duration would have no effect.
If you have the ability to execute code when the animation has finished this should work.
Add a variable to use as a lock rather than is(:animating).
On the click, check if the lock is set. If not, set the lock, start the process, then release the lock when the fadeIn finishes.
var blockAnimation = false;
$('#tab-list li a').click(
function() {
if(blockAnimation != true){
blockAnimation = true;
var targetTab = $(this).attr('href');
if ($(targetTab).is(':hidden')) {
$('#tab-list li').removeClass('selected');
var targetTabLink = $(this).parents('li').eq(0);
$(targetTabLink).addClass('selected');
$('.tab:visible').fadeOut('slow',
function() {
$(targetTab).fadeIn('slow', function(){ blockAnimation=false; });
}
);
}
}
return false;
}
);
Well this is how i did it, and it worked fine.
$(document).ready(function() {
$(".clickitey").click(function () {
if($("#mdpane:animated").length == 0) {
$("#mdpane").slideToggle("slow");
$(".jcrtarrow").toggleClass("arrow-open");
}
});
});
this is not doing what your code does ofcourse this is a code from my site, but i just like to point how i ignored the clicks that were happening during the animation. Please let me know if this is inefficient in anyway. Thank you.
I toyed around with the code earlier and came up with the following modification which seems to work:
$('#tab-list li a').click(
function() {
$('.tab:animated').stop(true, true);
var targetTab = $(this).attr('href');
if ($(targetTab).is(':hidden')) {
$('#tab-list li').removeClass('selected');
var targetTabLink = $(this).parents('li').eq(0);
$(targetTabLink).addClass('selected');
$('.tab:visible').fadeOut('slow',
function() {
$(targetTab).fadeIn('slow');
}
);
}
return false;
}
);
All that happens is, when a new tab is clicked, it immediately brings the current animation to the end and then begins the new transition.
one way would be this:
$('#tab-list ul li').one( 'click', loadPage );
var loadPage = function(event) {
var $this = $(this);
$global_just_clicked = $this;
var urlToLoad = $this.attr('href');
$('#content-area').load( urlToLoad, pageLoaded );
}
$global_just_clicked = null;
var pageLoaded() {
$global_just_clicked.one( 'click', loadPage );
}
As you can see, this method is fraught with shortcomings: what happens when another tab is clicked before the current page loads? What if the request is denied? what if its a full moon?
The answer is: this method is just a rudimentary demonstration. A proper implementation would:
not contain the global variable $global_just_clicked
not rely on .load(). Would use .ajax(), and handle request cancellation, clicking of other tabs etc.
NOTE: In most cases you need not take this round-about approach. I'm sure you can remedy you code in such a way that multiple clicks to the same tab would not affect the end result.
jrh.
One way to do this to use timeStamp property of event like this to gap some time between multiple clicks:
var a = $("a"),
stopClick = 0;
a.on("click", function(e) {
if(e.timeStamp - stopClick > 300) { // give 300ms gap between clicks
// logic here
stopClick = e.timeStamp; // new timestamp given
}
});

Categories

Resources