if ignores the condition JQuery - javascript

I'm trying to set up a div that can only be clicked once, but my if keeps ignoring the condition and I really dont know why.
$(document).ready(function() {
var defaultState = true;
if (defaultState) {
defaultState = false;
$("#element").click(function() {
//Do stuff to elements
}
});
I tried solving it a different way. I want this condition only to fill one div with context from another one, but only one single time. So I tried making the condition like this: if($("#element").html().length === 0) I even checked with the console for the value of my condition, and even if it was at 5000, clearly not 0 anymore, it kept ignoring my condition and went into the if.

Once you bind the click handler, it's bound. From that point, until you unbind it, that handler will always be triggered.
It sounds like one() would be what you're looking for:
$('#element').one('click', function() {
//...
});
That will only trigger once.

The event handler is already attached that first time through, right after the document.ready runs.
You can just use the jQuery .one() event handler.
jQuery .one() documentation
$("#element").one('click', function() {
//Do stuff to elements
});

$(document).ready(function() {
$("#element").one('click', function() {
//Do stuff to elements
});
});
OR
$("#element").on('click', function(){
//Do what you want
});
//Later in your code
$("#element").off('click');
If you're set on using a flag variable you can do it like this too:
$(document).ready(function() {
var defaultState = true;
$("#element").click(function(e) {
if (defaultState) {
//Do what you want
}
defaultState = false;
}
});

Once you have added a event listener $("#element").click(function() { it will be bounded to that element. But what you can do it to put your if inside the click function and give false to your flag variable once inside the if.
The advantage is you can give the variable true again, and you click will run "again".
$(document).ready(function () {
var defaultState = true;
$("#element").click(function () {
if (defaultState) {
defaultState = false;
//Do stuff to elements
} else {
return false;
}
});
});

Related

Re-binding JQuery events

I have a series of JQuery events, as an example, below
<script>
$("#target").click(function() {
..
});
$("#anothertarget").mouseout(function() {
...
});
$("#someselector").scroll(function() {
...
});
... other JQuery events
</script>
How do I "unbind" all these events from the document so they will all stop working and re-bind them all again later without hard coding them ?
There's a couple things you can do but either way you'd need to set conditions for the events:
You could create an event that would have a conditional that will turn the event on or off.
You could set a variable within the condition that would be either true or false, and then have that variable lead to a bind or unbind event.
if(some condition is true){
$("#target").on("click", function() {
});
}
//your scenario may not fit this code exactly but you would need to have conditions that bind or unbind events
var temp = true;
if(some condition is true){
$("#target").on("click", function() {
temp = false
});
};
if (temp == false){
$('#target').off("click",function(){
})
};
//the answer below by JagsSparrow is a pretty good way too
You can create bindAll & unBindAll functions and call them dynamically whenever required.
function bindAll(){
$("#target").click(function() {
..
});
$("#anothertarget").mouseout(function() {
...
});
$("#someselector").scroll(function() {
...
});
}
function unBindAll(){
$("#target").off('click');
$("#anothertarget").off('mouseout');
$("#someselector").off('scroll');
}
//To bind function call
bindAll();
//To unbind function call
unBindAll();
EDIT:
We can store object of events and bind and unbind them as below
var allEvents = {
'#target':{
event:'click',
func:function(){
console.log('click')
}
},
'#anothertarget':{
event:'mouseout',
func:function(){
console.log('mouseout')
}
},
'#someselector':{
event:'scroll',
func:function(){
console.log('scroll')
}
}
}
function bindUnbindAll(isBind){
for(var selector in allEvents){
// Here we can carefully filter some events to bind and unbind
var obj = allEvents[selector];
if(isBind)
$(selector).on(obj.event,obj.func.bind(this));
else
$(selector).off(obj.event);
}
}
//to bind function call
bindUnbindAll(true);
//To unbind function call
bindUnbindAll(false);
To unbind Off, unbind can be used to remove the event, like:
$('#target').unbind('click');
To bind
$('#target').bind('click', function() { /* Do stuff */ });
You can put code in functions to bind/unbind events on your objects. Hope this helps!

jquery if clicked multiple times

This is just a small piece of code of my function. The function is by default false, when you click on the #my-button the function will be true and run.
But now I want that when you click on the same button again, the function will be false again and should stop working.
And that should he be doing every time you click the button (it would be great if this is also possible with classes instead of the id)
$('#my-button').toggle(function () {
sliderPaused = true;
}, function () {
sliderPaused = false;
});
I use a toggle function, only this does not work for me. Is there something wrong at my code?
$('#my-button').click(function () {
if (sliderPaused) sliderPaused = false;
else sliderPaused = true;
});

Do I need to remove and replace event handlers with JQuery to swap them?

I want the events click and touchstart to trigger a function.
Of course this is simple with JQuery. $('#id').on('click touchstart', function{...});
But then once that event is triggered, I want that same handler to do something else when the events are triggered,
and then later, I want to go back to the original handling function.
It seems like there must be a cleaner way to do this than using $('#id').off('click touchstart'); and then re-applying the handler.
How should I be doing this?
You can create a counter variable in some construct in your javascript code that allows you to decide how you want to handle your event.
$(function() {
var trackClicks = (function() {
var clicks = true;
var getClicks = function() {
return clicks;
};
var eventClick = function() {
clicks = !clicks;
};
return {
getClicks: getClicks,
eventClicks: eventClicks
}
})();
$('#id').on('click touchstart', function {
if (trackClicks.getClicks()) {
handler1();
} else {
handler2();
}
trackClicks.eventClick();
});
function handler1() { //firsthandler};
function handler2() { //secondhandler};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
The way I would do this is by creating a couple of functions for the handler function to call based on certain flags. Sudo code would be something like this:
function beginning_action() {
...
}
function middle() {
...
}
var beginning_state = true;
$('#id').on('click touchstart', function{
if(beginning_state) {
beginning_action();
} else {
middle();
}
});
Then all you need to do is change the variable beginning_state to change which function is called. Of course you would give them better names that describe what they do and not when they do it.
Additionally, if you want the handler to call more than two functions you can change the beginning_state variable from a boolean to an int and check it's value to determine which function to call.
Good luck!

Toggle window.location in jQuery/javascript

What I am trying to achieve is that whenever you click an image, it changes the window.location url, toggling it between '#' and '#footer'. Right now, all I have is this:
<script>
function clickarrow(){
var rd=Math.floor(Math.random()*11)
if (rd > 5){
window.location="#footer";
}
else{
window.location="#";
}
}
</script>
As you can see, this makes a 50:50 chance of either change being made. It works as a temparary fix, but sometimes you have to click up to 6 times for it to take effect.
Is there a way of doing this that properly toggles the window.location?
I am using jQuery 1.9.
If you're trying to reliably toggle the hash, rather than using a random chance, try something like this:
function clickarrow(){
var showFooter = true;
return function () {
if (showFooter) {
window.location.hash = "footer";
} else {
window.location.hash = "";
}
showFooter = !showFooter;
}
}
jQuery(function () {
jQuery('#myToggleLink').click(clickarrow());
});
Note: Normally when binding events, a function reference must be passed in. Here, I'm invoking clickarrow() since it returns a function by design. The returned function encapsulates the toggle variable via closure.
you can use data attribute to tell what is next step:
$('#arrow').click(function() {
if ($(this).data('footer'))
{
window.location="#footer";
$(this).data('footer', 'false');
alert('b');
}
else
{
window.location="#";
$(this).data('footer', 'true');
alert('a');
}
});

Function becomes undefined after first trigger

I have a block of code like so:
function doSomething() {
someVar.on("event_name", function() {
$('#elementId').click(function(e) {
doSomething();
});
});
}
// and on document ready
$(function () {
$('#anotherElemId').click(function () {
doSomething();
});
});
The problem that I'm encountering is that when I call doSomething() from anotherElemId click event(that is binded on document ready) it works as expected, but calling it recursively from elementId click doesn't work.
Any ideas? Thinking is something trivial that I'm missing.
Is someVar an actual jQuery reference to a dom element? (e.g. $('#someitem'))
The second problem is you cant put a .click event inside a function that you would like to instantiate later on. If you are trying to only allow #elementId to have a click event AFTER some previous event, try testing if a tester variable is true:
var activated = false;
$(function () {
$('#anotherElemId').click(function () {
activated = true;
});
$('#secondElemId').on("event_name", function() {
if (activated) {
// code that happens only after #anotherElemId was clicked.
}
});
});

Categories

Resources