Toggle window.location in jQuery/javascript - 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');
}
});

Related

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!

How to call javascript function immediately rather than on scroll

I have a piece of javascript code here. When a hyperlink is clicked, the load_button() function is called which just sets the variable load_switch to true. I have a piece of code inside $(window).scroll(function() { which will fire the code when the user scrolls. So at the moment, the user clicks the hyperlink to set the variable to true, and then my load_posts function (which I omitted from the code I included to make it easier to read, see below) fires when the user scrolls.
I would like to know how I can make the function fire without the user having to scroll first to activate it. I am editing a previously programmed function which used to be an infinite scroll (hence the function being called when the user scrolls). Here is my javascript:
<script language="javascript">
var load_switch = false;
function load_button(){
load_switch = true;
}
$(document).ready(function() {
$('.loader').hide();
var load = 0;
$(window).scroll(function() {
if(load_switch) {
//load_posts function goes here
}
});
});
</script>
Name your function
var load_switch = false;
function load_button(){
load_switch = true;
}
// Name your function instead of defining it inline
function onScroll() {
if(load_switch) {
//load_posts function goes here
}
}
$(document).ready(function() {
$('.loader').hide();
var load = 0;
$(window).scroll(onScroll);
// Call it whenever you'd like
onScroll();
});
You can use triggerHandler:
$(window).triggerHandler('scroll');
Note this will run all event handlers. If you don't want that, you need to store the desired event handler in a variable:
function handleScroll() {
//load_posts function goes here
}
function load_button(){
$(window).on('scroll', handleScroll);
}
$(document).ready(function() {
$('.loader').hide();
handleScroll(); // Call it manually
});
Also note your approach was bad. Instead of running the event handler always and exiting if a boolean flag is false, get rid of that flag and add or remove the event handler instead of setting the flag to true or false.

Defining generic function jquery

I have a simple function that shows a div when the user clicks on a given checkbox. I'd like to have the same behaviour on another checkbox, so that's why I'd like to generalize it as a function passing the element to be shown.
But I'm not aware of the syntax on Jquery to do so. And it's triggering automatically when the page loads. Does anybody has an idea?
Code:
$(document).ready(function() {
$("#transcricao").change(
function(){
if ($('.form_transcr').css('display') === 'none') {
$('.form_transcr').fadeIn();
} else {
$('.form_transcr').fadeOut();
}
}
); //This is working fine!
$("#traducao").change( show_hide($('.form_trad')) );
//This is auto-trigerring without user action...
});
Here's my function:
function show_hide($elm){
//This is the "generalized" function that I'd like to use on both
//checkboxes, just passing the element.
if ($($elm).css('display') === 'none') {
$($elm).fadeIn();
} else {
$($elm).fadeOut();
}
}
Its auto-triggering without user action because you are invoking it.
Use
$("#traducao").change(function () {
show_hide($('.form_trad'));
});
As you are passing jQuery object so use it directly
function show_hide($elm) {
//This is the "generalized" function that I'd like to use on both
//checkboxes, just passing the element.
if ($elm.css('display') === 'none') {
$elm.fadeIn();
} else {
$elm.fadeOut();
}
}
The argument to .change() should be a function. You're not passing a function, you're calling the function.
$("#traducao").change(function() {
show_hide($('.form_trad'));
} );
BTW, your show_hide function seems to be equivalent to jQuery's fadeToggle method, so it can be:
$("#traducao").change(function() {
$(".form_trad").fadeToggle();
});

if ignores the condition JQuery

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

JQuery, how to access click object after ajax call?

this seems like it should be straightforward, but I'm having trouble getting it to work.
I have a .click bind to many buttons of a certain class. When that button is clicked, it passes its id to a $.post call for processing.
When the $.post call returns successfully, I'd like to remove the button and add a message to the container, but I can't seem to even access the button at that point.
Here is the .click bind:
$('.button').click(function() {
$.post('process.php', {
action: 'checkit'
},
function(result) {
if (result == 'win') {
// Access the button that was pressed with jQuery
}
else {
alert("fail");
}
});
});
I've tried, $(this), this, and also setting a variable like var trigger=this as I enter the initial click function, but none of these are working. I get undefined, or it points to the actual JQuery object, not the button.
Does anyone have any insight into how I can access the button that was clicked at that point, using a jQuery wrapper, essentially something like $( triggered button ).html() so that I can manipulate the correct button?
Thanks for your time.
$('.button').click(function() {
var clicked = $(this);
....
Use a local variable for temporary storage.
try this
$('.button').click(function() {
var $button = $(this);
$.post('process.php', {
action: 'checkit'
},
function(result) {
if (result == 'win') {
$button.doStuff();
}
else {
alert("fail");
}
});
});
It's quite easy to do:
$(this).foo('bar');
Is
$('.button').click(function() {
$.post('process.php', {
action: 'checkit'
},
function(result) {
if (result == 'win') {
$(this).html('something');
}
else {
alert("fail");
}
}.bind(this));
});
working?
jsfiddle example of what you are attempting. Click on the text. Just keep a local variable.

Categories

Resources