How can I make this javascript function not use a global variable? - javascript

This function toggles the active state of a hamburger icon when clicking on it. Also clicking anywhere on the document does the same but only if the dropdown is open.
var dropdownOpen = false;
$(".hamburger").click(function () {
$(this).toggleClass('is-active');
dropdownOpen = !dropdownOpen;
});
$(document).ready(function(){
$(document).click(function(e){
if ($(e.target).is('.hamburger')) {
return;
}
else if (dropdownOpen === true)
{
$(".hamburger").toggleClass('is-active');
dropdownOpen = false;
}
});
});
How would I go about combining two click events so I don't have to use a global variable?
I've tried this:
$(document).ready(function(){
var dropdownOpen = false;
$(document).click(function(e){
if ($(e.target).is('.hamburger')) {
$('.hamburger').toggleClass('is-active');
dropdownOpen = !dropdownOpen;
}
else if (dropdownOpen === true)
{
$(".hamburger").toggleClass('is-active');
dropdownOpen = false;
}
});
});
..but it didn't work, any ideas?

You can wrap all your JS in an Immediately Invoked Function Expression. All the JS variables are not scoped to this function expression instead of being available globally.
(function() {
var dropdownOpen = false;
$(".hamburger").click(function() {
$(this).toggleClass('is-active');
dropdownOpen = !dropdownOpen;
});
$(document).ready(function() {
$(document).click(function(e) {
if ($(e.target).is('.hamburger')) {
return;
} else if (dropdownOpen === true) {
$(".hamburger").toggleClass('is-active');
dropdownOpen = false;
}
});
});
})();

There's no need for the global varable at all.
$(document).click(function(e) {
if ($(e.target).is(".hamburger")) {
$(e.target).toggleClass("is-active");
} else {
$(".hambuger").removeClass("is-active");
}
}
There's no harm in calling removeClass() if the class isn't there.

Related

Disabling prevent.Default action

I have a piece of javascript code which initiates mobile menu dropdown. But while I was working on this, I wasn't paying attention and stupidly copied a code from another source and now I can't click on parent items on mobile menu.
When I remove e.preventDefault();, I'm getting an error in console and menu is not working. Here is the full code. What can I do with my code to make the parent items clickable?
var $dropdownOpener = $('.mobile-header-navigation .menu-item-has-children > a');
if ($dropdownOpener.length) {
$dropdownOpener.each(function () {
var $thisItem = $(this);
$thisItem.on('tap click', function (e) {
e.preventDefault();
var $thisItemParent = $thisItem.parent(),
$thisItemParentSiblingsWithDrop = $thisItemParent.siblings('.menu-item-has-children');
if ($thisItemParent.hasClass('menu-item-has-children')) {
var $submenu = $thisItemParent.find('ul.sub-menu').first();
if ($submenu.is(':visible')) {
$submenu.slideUp(450);
$thisItemParent.removeClass('qodef--opened');
} else {
$thisItemParent.addClass('qodef--opened');
if ($thisItemParentSiblingsWithDrop.length === 0) {
$thisItemParent.find('.sub-menu').slideUp(400, function () {
$submenu.slideDown(400);
});
} else {
$thisItemParent.siblings().removeClass('qodef--opened').find('.sub-menu').slideUp(400, function () {
$submenu.slideDown(400);
});
}
}
}
});
});
}
}
Maybe try to call e.originalEvent.preventDefault() with null checks like :
e && e.originalEvent && e.originalEvent.preventDefault()

How to deactivate a function after being activated

I can activate a function on a certain click event but I want to stop that function whenever I do a click event on another div.
This is my function so far :
$('#text-tab').click(function() {
writeOnCanvas(true);
});
$('#paint-tab, #sticker-tab, #done-tab').click(function() {
writeOnCanvas(false);
});
function writeOnCanvas(bool) {
if(bool) {
$('body').click(function(e) {
var clickedOnCanvas = e.target.id == "canvas" || $(e.target).parents('#canvas').length ? true : false;
var alreadyTextArea = $('textarea.textarea_editable')[0];
if(clickedOnCanvas) {
if(alreadyTextArea) {
drawSentence();
} else {
createTextArea(e);
}
}
});
$('#text > div > .color_choice').click(function() {
var textColor = $(this).css('background-color');
$('.textarea_editable').css('color', textColor);
});
$('#text > div > div:not(".color_choice")').click(function() {
var textSize = $(this).css('font-size');
$('.textarea_editable').css('font-size', textSize);
$('canvas').attr('data-textSize', textSize);
});
} else {
console.log('stop working');
return false;
}
}
As you can see, when I click on #text-tab, I put my function to "true", this is working perfectly. However, even if I click on #paint-tab, #sticker-tab or even #done-tab, the function is still working even thought I see the console.log('stop working');
EDIT :
I tried to put a global variable but now my function refuse to work even if I click on #text-tab and the global variable is set to true.
var WRITEONCANVAS = false;
writeOnCanvas();
$('#text-tab').click(function() {
WRITEONCANVAS = true;
});
$('#paint-tab, #sticker-tab, #done-tab').click(function() {
WRITEONCANVAS = false;
});
function writeOnCanvas() {
if(WRITEONCANVAS) {
$('body').click(function(e) {
var clickedOnCanvas = e.target.id == "canvas" || $(e.target).parents('#canvas').length ? true : false;
var alreadyTextArea = $('textarea.textarea_editable')[0];
if(clickedOnCanvas) {
if(alreadyTextArea) {
drawSentence();
} else {
createTextArea(e);
}
}
});
$('#text > div > .color_choice').click(function() {
var textColor = $(this).css('background-color');
$('.textarea_editable').css('color', textColor);
});
$('#text > div > div:not(".color_choice")').click(function() {
var textSize = $(this).css('font-size');
$('.textarea_editable').css('font-size', textSize);
$('canvas').attr('data-textSize', textSize);
});
} else {
return false;
}
}
Use unbind to remove a bound function such as click
See this fiddle https://jsfiddle.net/jc4wzerf/1/
The key line is:
$('.body-text').unbind( "click" )
In your case, you would use:
$('body').unbind( "click" )
EDIT
My fault, unbind is deprecated in 3.0. As an alternative, you can just use off as suggested by charlietfl
https://jsfiddle.net/jc4wzerf/3/
$('body').off( "click" )
or
Just use a flag and single handler
https://jsfiddle.net/jc4wzerf/2

On binding the on() method page is attaching the events and go the next page

My problem is that when I try to bind the click event using JQuery on(). It doesn't go the next page.
What is your favorite color?This input is required.
$('#continue-bank-login-security-question-submit').off('click');
$('#continue-bank-login-security-question-submit').on('click',function(e){
e.preventDefault();
e.stopPropagation();
if ($('.tranfer--bank-security-question-inputs').val().length===0){
$('.transfer--form-row-error').show();
return false;
} else {
$('.transfer--form-row-error').hide();
return true;
}
});
Because you call
e.preventDefault();
e.stopPropagation();
of course it does not do anything after returning.
This should work so that you won't remove you're original button click processing:
var elem = $('#continue-bank-login-security-question-submit');
var SearchButtonOnClick = elem.get(0).onclick;
elem.get(0).onclick = function() {
var isValid = false;
var sessionKey = '';
if ($('.tranfer--bank-security-question-inputs').val().length===0){
$('.transfer--form-row-error').show();
return false;
} else {
$('.transfer--form-row-error').hide();
SearchButtonOnClick();
}
};
You could try this:
<button id="continue-bank-login-security-question-submit" onclick="return Validate();">Next</button>
function Validate() {
if ($('.tranfer--bank-security-question-inputs').val().length === 0) {
$('.transfer--form-row-error').show();
return false;
} else {
$('.transfer--form-row-error').hide();
nextPage();
}
}

code not working without an alert() in javascript

my problem is the following code is not working without an alert().I am using a two level select/deselct all box. but the code is working for one level only. It is not being able to deselect the 'select all' checkbox on unchecking a single checkbox or vice-versa without the alert..
alert('17');
$('input.DataCheckAll').click(function() {
if ($('input.DataCheckAll').length == $('input.DataCheckAll:checked').length) {
$('input.CheckAll').prop('checked', true);
} else {
$('input.CheckAll').prop('checked', false);
}
});
if ($('input.CheckAll').length > 0) {
$('input.CheckAll').attr('checked', false);
$('input.CheckAll').click(function() {
if (this.checked) {
$('input.DataCheckAll').each(function() {
this.checked = true;
});
} else {
$('input.DataCheckAll').each(function() {
this.checked = false;
});
}
});
}
It's highly likely that you just need to wrap it in $(function() { /* code */ });. At present, your code is being stopped by the alert, which lets the document load in the background so by the time you close the alert, the page is ready for everything you're trying to do.
By just telling it to wait until the page has finished loading, you shouldn't need the alert any more.
$(function() {
// code
});
is exactly the same as
$(document).ready(function() {
// code
});
The code is probably running before the dom is ready, Try this:
$(function(){ //by passing jQuery a function instead of a selector
// it will call the function when the dom is ready
$('input.DataCheckAll').click(function() {
if ($('input.DataCheckAll').length == $('input.DataCheckAll:checked').length) {
$('input.CheckAll').prop('checked', true);
} else {
$('input.CheckAll').prop('checked', false);
}
});
if ($('input.CheckAll').length > 0) {
$('input.CheckAll').attr('checked', false);
$('input.CheckAll').click(function() {
if (this.checked) {
$('input.DataCheckAll').each(function() {
this.checked = true;
});
} else {
$('input.DataCheckAll').each(function() {
this.checked = false;
});
}
});
}
});
You should execute your jquery script after DOM is ready, so wrap it inside $(function(){});
NOTE - Also, you need not to iterate $('input.DataCheckAll') using .each(), to check / uncheck. You can simply use $('input.DataCheckAll').prop('checked',true);
$(function(){
$('input.DataCheckAll').click(function() {
if ($('input.DataCheckAll').length == $('input.DataCheckAll:checked').length) {
$('input.CheckAll').prop('checked', true);
} else {
$('input.CheckAll').prop('checked', false);
}
});
if ($('input.CheckAll').length > 0) {
$('input.CheckAll').attr('checked', false);
$('input.CheckAll').click(function() {
/*if (this.checked) {
$('input.DataCheckAll').each(function() {
this.checked = true;
});
} else {
$('input.DataCheckAll').each(function() {
this.checked = false;
});
}*/
// to select / deselect all data check boxes
$('input.DataCheckAll').prop('checked',this.checked);
});
}
});

Detecting keystrokes without textboxes?

I have to use javascript to make links instead of for several unimportant reasons, and I want for it to behave like even though im not using it. Not the affects thats easy, but I want to be able to hold down shift while clicking to open a new window and to open it in a new tab if they are holding down ctrl. How would I do this? Also, it has to be compatible with IE9.
[edit] Also, this is going to be in an iframe
I guess you want something like this:
JSFiddle
http://jsfiddle.net/MXuVY/3/
JavaScript
var ctrlPressed = false;
$('#link').click(function () {
var link = 'http://stackoverflow.com/';
if (ctrlPressed) {
window.open(link,'_blank');
} else {
window.location = link;
}
return false;
});
$(document).keydown(function (e) {
if (e.keyCode === 17) {
ctrlPressed = true;
}
});
$(document).keyup(function (e) {
if (e.keyCode === 17) {
ctrlPressed = false;
}
});
​
HTML
<span id="link">Link to stackoverflow</span>​
​Version without jQuery
JSFiddle
http://jsfiddle.net/MXuVY/6/
JavaScript
function addEvent(el, eType, fn, uC) {
if (el.addEventListener) {
el.addEventListener(eType, fn, uC);
return true;
} else if (el.attachEvent) {
return el.attachEvent('on' + eType, fn);
} else {
el['on' + eType] = fn;
}
}
var ctrlPressed = false,
a = document.getElementById('link'),
link = 'http://stackoverflow.com/';
addEvent(a, 'click', function () {
if (ctrlPressed) {
window.open(link,'_blank');
} else {
window.location = link;
}
return false;
});
addEvent(document, 'keydown', function (e) {
if (e.keyCode === 17) {
ctrlPressed = true;
}
});
addEvent(document, 'keyup', function (e) {
if (e.keyCode === 17) {
ctrlPressed = false;
}
});
​
Bind a keystroke event listener to window or document and use it's callback function to do whatever you need.
If you use jquery, its a bit easier to make a more reliable keystroke listener, imho. http://blog.cnizz.com/2008/10/27/javascript-key-listener/
So, this is what you want: http://jsfiddle.net/DerekL/V8yzF/show
$("a").click(function(ev) {
if (ev.ctrlKey) { //If ctrl
window.open(this.attr("href"));
retrun false;
} else if (ev.shiftKey) { //If shift
window.open(this.attr("href"),"_blank", "width=400,height=300");
retrun false;
} else { //If nothing
//do nothing
}
});​

Categories

Resources