window is not loading immediately after clicking a link - javascript

When I click an anchor link, the current page should be loaded again immediately:
<a href="javascript:void(0);" class="BackToFirst"
onclick="popNav('BackToFirst');">Back</a>
function popNav(type) {
if(type == "BackToFirst") {
$(".first").show();
$(".second").hide();
$('.BackToFirst').click(function() {
document.location.href = window.location.href;
});
}
}
I expect that when a user clicks on the link, the current page will load immediately but it is taking some time to load.

It is unclear what you are trying to do.
show/hide is immediately undone when you reload the page
it is recommended to use location.reload(1) instead of setting the supposedly read-only document.location
you might want to use e.preventDefault instead of the javascript void
Are you absolutely sure this is not an X/Y problem? Can you explain the actual usecase?
var current = sessionStorage.getItem("which"); // does not run in a snippet
current = current ? current.split("|") : []
if (current.length) {
$("." + current[0]).show();
$("." + current[1]).hide();
}
$(".BackToFirst").on("click", function(e) {
e.preventDefault();
$(".first").show();
$(".second").hide();
sessionStorage.setItem("which", "first|second")
setTimeout(function() {
location.reload(1); // are you absolutely sure this is not an X/Y problem?
}, 500); //let the show/hide sink in
});
Back

Your Click handler is only assigning a new click handler to the link, try this which just directly navigates:
function popNav(type){
if(type=="BackToFirst")
{
$(".first").show();
$(".second").hide();
document.location.href = window.location.href;
}
}
I think that you got two concepts mixed up, the above code attaches a DOM event to the link directly on it, the other way would be to use JQuery to attach an event to that button like so:
HTML:
Back
Script:
$('.BackToFirst').click(function(){
$(".first").show();
$(".second").hide();
document.location.href = window.location.href;
});
If you still want to check the type then data attributes are a nice way to go when working with JQuery:
Back
$('.BackToFirst').click(function(){
if($(this).data('linktype') == 'BackToFirst'){
$(".first").show();
$(".second").hide();
document.location.href = window.location.href;
}
});

I think you are overcomplicating your code. You are binding onClick after you click on the element. I think something like this should be better.
HTML:
Back
JS:
function onClickHandler(type){
if(type !== 'BackToFirst') {
return;
}
$(".first").show();
$(".second").hide();
location.reload();
}

Related

Intercept clicks, make some calls then resume what the click should have done before

Good day all, I have this task to do:
there are many, many many webpages, with any kind of element inside, should be inputs, buttons, links, checkboxes and so on, some time there should be a javascript that could handle the element behaviour, sometimes it is a simple ... link.
i have made a little javascript that intercepts all the clicks on clickable elements:
$( document ).ready(function() {
$('input[type=button], input[type=submit], input[type=checkbox], button, a').bind('click', function(evt, check) {
if (typeof check == 'undefined'){
evt.preventDefault();
console.log("id:"+ evt.target.id+", class:"+evt.target.class+", name:"+evt.target.name);
console.log (check);
$(evt.target).trigger('click', 'check');
}
});
});
the logic is: when something is cllicked, I intercept it, preventDefault it, make my track calls and then resme the click by trigger an event with an additional parameter that will not trigger the track call again.
but this is not working so good. submit clicks seams to work, but for example clicking on a checkbox will check it, but then it cannot be unchecked, links are simply ignored, I track them (in console.log() ) but then the page stay there, nothing happens.
maybe I have guessed it in the wrong way... maybe i should make my track calls and then bind a return true with something like (//...track call...//).done(return true); or something...
anyone has some suggestions?
If you really wanted to wait with the click event until you finished with your tracking call, you could probably do something like this. Here's an example for a link, but should be the same for other elements. The click event in this example fires after 2seconds, but in your case link.click() would be in the done() method of the ajax object.
google
var handled = {};
$("#myl").on('click', function(e) {
var link = $(this)[0];
if(!handled[link['id']]) {
handled[link['id']] = true;
e.preventDefault();
e.stopPropagation();
//simulate async ajax call
window.setTimeout(function() {link.click();}, 2000);
} else {
//reset
handled[link['id']] = false;
}
});
EDIT
So, for your example, this would look something like this
var handled = {};
$( document ).ready(function() {
$('input[type=button], input[type=submit], input[type=checkbox], button, a').bind('click', function(evt) {
if(!handled[evt.target.id]) {
handled[evt.target.id] = true;
evt.preventDefault();
evt.stopPropagation();
$.ajax({
url: 'your URL',
data: {"id" : evt.target.id, "class": evt.target.class, "name": evt.target.name},
done: function() {
evt.target.click();
}
});
} else {
handled[evt.target.id] = false;
}
});

X-Editable: stop propagation on "click to edit"

I have an editable element inside a div which itself is clickable. Whenever I click the x-editable anchor element, the click bubbles up the DOM and triggers a click on the parent div. How can I prevent that? I know it's possible to stop this with jQuery's stopPropagation() but where would I call this method?
Here's the JSFiddle with the problem: http://jsfiddle.net/4RZvV/ . To replicate click on the editable values and you'll see that the containing div will catch a click event. This also happens when I click anywhere on the x-editable popup and I'd like to prevent that as well.
EDIT after lightswitch05 answer
I have multiple dynamic DIVs which should be selectable so I couldn't use a global variable. I added an attribute to the .editable-click anchors which get's changed instead.
editable-active is used to know if the popup is open or not
editable-activateable is used instead to know if that .editable-click anchor should be treated like it is
$(document).on('shown', "a.editable-click[editable-activateable]", function(e, reason) {
return $(this).attr("editable-active", true);
});
$(document).on('hidden', "a.editable-click[editable-activateable]", function(e, reason) {
return $(this).removeAttr("editable-active");
});
The check is pretty much like you've described it
$(document).on("click", ".version", function() {
$this = $(this)
// Check that the xeditable popup is not open
if($this.find("a[editable-active]").length === 0) { // means that editable popup is not open so we can do the stuff
// ... do stuff ...
}
})
For the click on the links, simply catch the click event and stop it:
$("a.editable-click").click(function(e){
e.stopPropagation();
});
The clicks within X-editable are a bit trickier. One way is to save a flag on weather the X-editable window is open or not, and only take action if X-editable is closed
var editableActive = false;
$("a.editable-click").on('shown', function(e, reason) {
editableActive = true;
});
$("a.editable-click").on('hidden', function(e, reason) {
editableActive = false;
});
$("div.version").click(function(e) {
var $this;
$this = $(this);
if(editableActive === false){
if ($this.hasClass("selected")) {
$(this).removeClass("selected");
} else {
$(this).addClass("selected");
}
}
});
Fixed Fiddle
It's not pretty, but we solved this problem with something like:
$('.some-class').click(function(event) {
if(event.target.tagName === "A" || event.target.tagName === "INPUT" || event.target.tagName === "BUTTON"){
return;
}
We're still looking for a solution that doesn't require a specific list of tagNames that are okay to click on.

Modify target url in onclick handler

Is it possible to modify the target URL in the onclick handler? How?
I don't want to use things like window.location = ... because it changes the browsers' behaviour (click vs ctrl-click, opening in new tab, opening in particular window/frame etc...). I want a clean solution - just change the url and the rest should be done itself as it would normally be.
$(...).click(function () {
if (check_some_condition)
// modify target url here...
// do not want to do window.location= - this is not clean
// as it changes the browsers' behaviour (ctrl-click, opening in particular window/frame etc.)
return true;
});
Try
​$(function(){
$("#theLink").click(function(){
$(this).attr("href","http://tnbelt.com");
});
});​​​​
Edit: Updated code because the event handler script is executed first and then the default action takes place.
Added below version to show you that you can use .click as you didn't notice the quirks mode link I shared with you. DEMO
$(document).ready (function () {
$('#changeMe'). click (function (e) {
var goLucky = Math.floor(Math.random()*12);
if (goLucky % 2 == 0) {
this.href = "http://www.google.com";
} else {
this.href = "http://www.hotmail.com";
}
});
});
Commented e.preventDefault(); & $(this).click() as it is not required..
DEMO
$(document).ready (function () {
$('#changeMe').one ('click', function (e) {
//e.preventDefault();
this.href = "http://www.google.com";
//$(this).click();
});
});
Let us consider a hidden anchor tag
<a id="linkId" href="myPageToGo.html" class="thickbox" title="" style="visibility:hidden;">Link</a>
Then you can simulate the anchor click in your code...
$(...).click(function () {
if (check_some_condition)
$('#linkId').click();
return true;
});
EDIT - Alternative way
Wrap the element clicked inside a anchor tag...
$(...).click(function () {
if (check_some_condition)
$(this).wrap('<a id="new1" />');
$('#new1').click();
return true;
});
Yup.
$(this).attr('href', 'http://example.com/');
A lot of the answers including the top comment have missed out on an important point. If a user simply right clicks the URL to perhaps open in a new tab/window, this method won't work because you're directly requesting at the location specified by the 'href' URL instead of going through the onclick event.
You could try the same at this demo fiddle mentioned on Gourneau's post.
http://jsfiddle.net/skram/PtNfD/7/
$(document).ready (function () {
$('#changeMe').one ('click', function (e) {
this.href = "http://www.google.com";
});
});

Prevent page scroll after click?

After clicking on the link, Click Me, the page scrolls back to the top. I do not want this. How can fix it?
Example: http://jsfiddle.net/Y6Y3Z/
Scroll-bar:
function myalert() {
var result = true;
//var hide = $('.alert').fadeOut(100);
//var css = $('#appriseOverlay').css('display','none');
var $alertDiv = $('<div class="alert">Are you sure you want to delete this item?<div class="clear"></div><button class="ok">no</button><button class="cancel">yes</button></div>');
var link = this;
$('body').append($alertDiv);
$('.ok').click(function () {
$('.alert').fadeOut(100);
$('#appriseOverlay').css('display', 'none');
callback(true, link);
});
$('.cancel').click(function () {
$('.alert').fadeOut(100);
$('#appriseOverlay').css('display', 'none');
callback(false, link);
});
$alertDiv.fadeIn(100);
$('#appriseOverlay').css('display', 'block');
return result;
};
$('.click').click(myalert);
function callback(result, link) {
//
if(result){
}
}
You only need to change the "#" to "javascript:void(0)" on HTML code:
Click Me
Another solution is add a "/" after the "#":
Click Me
The reason that it is going to the top of the page is because your anchor tag has a hash symbol as the href. The hash syntax allows you to refer to a named anchor in the document, with the link taking you to that place in the document. The default action for an anchor tag when you click on it and the href refers to a named anchor that doesn't exist is to go to the top of the page. To prevent this cancel the default action by returning false from the handler or using preventDefault on the event.
function myalert(e) {
e.preventDefault(); // <-- prevent the default action
...
return false; // <-- alternative way to prevent the default action.
};
simply prevent the default function (jump to #marker) from executing: http://jsfiddle.net/Y6Y3Z/1/

jQuery .load() How to prevent double loading from double clicking

I am using jQuery load() function to load some pages into container. Here is the code:
$('div.next a').live('click',function() {
$('.content').load('page/3/ #info','',function(){
//do something
});
return false;
});
Everything works just fine but the problem is when I quickly double click the div.next link, from console I see that it loads the page twice because I did a quick double click. I could even make it 3 clicks and it will load it 3 times and show in console smth like that:
GET http://site/page/3/ 200 OK 270ms
GET http://site/page/3/ 200 OK 260ms
My question is how to prevent such double clicking and not to let load the target page more then once no matter how many times it was clicked.
Thank you.
Whatever happened to good ol' JavaScript? Why are you all trying to figure it out with pure jQuery?
var hasBeenClicked = false;
$('div.next a').live('click',function() {
if(!hasBeenClicked){
hasBeenClicked = true;
$('.content').load('page/3/ #info','',function(){
//do something
//If you want it clickable AFTER it loads just uncomment the next line
//hasBeenClicked = false;
});
}
return false;
});
As a side note, never never never use .live(). Use .delegate instead like:
var hasBeenClicked = false;
$('div.next').delegate('a','click',function() {
if(!hasBeenClicked){
hasBeenClicked = true;
$('.content').load('page/3/ #info','',function(){
//do something
//If you want it clickable AFTER it loads just uncomment the next line
//hasBeenClicked = false;
});
}
return false;
});
Why? Paul Irish explains: http://paulirish.com/2010/on-jquery-live/
To answer your comment...
This could happen if you have your delegate function nested inside your AJAX call (.load(), .get(), etc). The div.next has to be on the page for this to work. If div.next isn't on the page, and this isn't nested, just do this:
$('#wrapper').delegate('div.next a','click',function() {
http://api.jquery.com/delegate/
Delegate needs the selector to be the parent of the dynamically added element. Then, the first parameter of delegate (div.next a in the last example) is the element to look for within the selected element (#wrapper). The wrapper could also be body if it's not wrapped in any element.
You could try using the jquery one method:
$("a.button").one("click", function() {
$('.content').load('page/3/ #info','',function(){
//do something
});
});
You could unbind the click event with die():
$(this).die('click').click(function() { return False; });
Or you could give the element a .clicked class once it is clicked:
$(this).addClass('clicked');
And check if that class exists when performing your logic:
$('div.next a').live('click',function() {
if (!$(this).is('.clicked')) {
$(this).addClass('clicked');
$('.content').load('page/3/ #info','',function(){
//do something
});
}
return false;
});
Store whether you're waiting for the load in a variable.
(function() {
var waitingToLoad = false;
$('div.next a').live('click',function() {
if (!waitingToLoad) {
waitingToLoad = true;
$('.content').load('page/3/ #info','',function(){
waitingToLoad = false;
//do something
});
}
return false;
});
})()

Categories

Resources