setting location.href does not work from a <a> click - javascript

This is code I took over from a colleague who left:
<input type="text" class="value" placeholder="0"></span><br>
Act Now
<script>
$('.act-a').click(function(){
if(parseInt($('.value').val())>0){
//window.location.href = window.location.origin + $(this).attr('url') + '?r=' + parseInt($('.value').val());
window.location.replace("www.google.com");
return true;
}
return false;
});
</script>
When I click on the link, I never get redirected to www.google.com. Originally what I want is to execute the commented code, but setting www.google.com to debug, I think to realize that my redirection is being ignored, and instead the original href from the is used!
How can I set window.location.href when a link has been clicked, adding a GET parameter?

return true; tells the browser to do the link's default action. So, the browser is following the link instead of running window.location.
Remove both the return statements, and instead add e.preventDefault();
$('.act-a').click(function(e){
e.preventDefault();
if(parseInt($('.value').val(), 10) > 0){
window.location.href = window.location.origin + $(this).attr('url') + '?r=' + parseInt($('.value').val(), 10);
}
});
P.S. You should add ,10 to parseInt to make sure the number is parsed as base 10.

Change reutrn true after window.location to return false;
$('.act-a').click(function(){
if(parseInt($('.value').val())>0){
//window.location.href = window.location.origin + $(this).attr('url') + '?r=' + parseInt($('.value').val());
window.location.replace("www.google.com");
return false;
}
return false;
});
Returning false on events such as click, submit and others prevent the default behavior of such event. Use return true only if you want to run a function and then let the event propagate to the other regular listeners such as following a link's href, continue normal form submission etc... This article is helpful for event bubbling basics: http://www.quirksmode.org/js/events_order.html

Related

window is not loading immediately after clicking a link

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

trigger change event except condition jquery

$('#query_txt').change(function() {
return window.location = $('#query_txt').data('url') + '/searches?query=' + $('#query_txt').val();
});
This event is triggered when it's made a change on input field #query_txt
However I want execute this code unless a user click on this link:
I have tried with this version with coffeescript but is not working:
unless $(".select2-search-choice-close").click()
$('#query_txt').change ->
window.location = $('#query_txt').data('url') + '/searches?query=' + $('#query_txt').val()
How can I do it?
Thank you!
Make a condition flag true when you click it. Or unbind to change in the click handler for your link.
Try this
var buttonClicked = false;
$('#query_txt').change(function() {
if(buttonClicked)
window.location = $('#query_txt').data('url') + '/searches?query=' + $('#query_txt').val();
});
$(".select2-search-choice-close").click(function(){
buttonClicked = true;
return false;
});
The fix to this question is in when click on close button and when click on suggestions text with select2.
Select2 returns an object in callback and it is possible check if it's added or removed there. Thank you to Eru.

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 ~ Adjusting href before following it

I have a link with a series of checkboxes, due to the legacy code, when the user clicks on a checkbox the value of it is appended as a comma deliminated list to the href.
The trouble is that now that I'm updating the code, I'm finding that the href is being followed quicker than the href is being adjusted, thus the list is being excluded.
I have tried using preventDefault() which is great, but I have no idea how to continue the default action after changing the href to include the selected values.
I should also mention that it is not viable to change it to a regular form, as there is an additional option set in a lightbox after submission. (Don't ask me why, it's lunacy in my book)
So far I've got to
$(function(){
$('#cnt-area form table tbody').dragCheck();
// I just split up the .each and .click to see if it mattered, which it doesnt
$('.multi_assign_link').each(function(){
$(this).click(function(e){
e.preventDefault();
var href = $(this).attr('href');
$('#cnt-area form input:checkbox').each(function(){
if($(this).attr('checked')){
if(href.search(','+$(this).val()) == -1){
href += ','+$(this).val();
}
}else{
var s = ','+$(this).val();
s.toString();
href = href.replace(s, '');
}
});
$(this).attr('href',href);
// Continue to follow the link
// Faking a user click here with $(this).click(); obviously throws a loop!
});
});
});
Just set the location to the adjusted href value and return false from the handler to avoid taking the original link.
$(function(){
$('#cnt-area form table tbody').dragCheck();
// I just split up the .each and .click to see if it mattered, which it doesnt
$('.multi_assign_link').each(function(){
$(this).click(function(e){
var href = $(this).attr('href');
$('#cnt-area form input:checkbox').each(function(){
if($(this).attr('checked')){
if(href.search(','+$(this).val()) == -1){
href += ','+$(this).val();
}
}else{
var s = ','+$(this).val();
s.toString();
href = href.replace(s, '');
}
});
location.href = href;
return false;
});
});
});

Categories

Resources