HTML button click opening 2 links in new tab - javascript

I have these buttons on frontend and only one is visible at a time. .btn-active hides the button.
Buy Now
Buy Now
on button click, I wanted to open the package link by concatenating package id in href in jquery.
jQuery('#starter-monthly').on('click', function(e) {
var href = jQuery(this).attr('href');
window.open(href + '?package='+24);
});
jQuery('#starter-yearly').on('click', function(e) {
var href = jQuery(this).attr('href');
window.open(href + '?package='+27);
});
but when I click the button, it opens 2 links in 2 separate tabs which are https://example.com/shop?packag=24 and https://example.com/shop/
I wanted to open only one link which is https://example.com/shop?packag=24
What I am doing wrong? Any solution?

Clicking on an anchor element (a tag) instructs the browser to open the link. Having target attribute further tells the browser to open it in a new window/tab. Now your code captures the click event and explicitly opens a new window (with proper url). However, that doesn't prevent the browser from carrying out the original action intended for all 'anchor' tags.
Basically you see two tabs opening, because one is opened by your code, and the other one by browser because of the click on anchor tag. You can suppress the default browser behaviour by calling preventDefault on the event object passed to your handler. Your code should be something like this:
jQuery('#starter-monthly').on('click', function(e) {
e.preventDefault();
var href = jQuery(this).attr('href');
window.open(href + '?package='+24);
});
jQuery('#starter-yearly').on('click', function(e) {
e.preventDefault();
var href = jQuery(this).attr('href');
window.open(href + '?package='+27);
});

Related

how to change href during onclick event

I am trying to create a dynamic hyperlink that will download an image retrieved from the server.
The code I am using:
HTML:
<a class="btn" id="controlDownloadJPEG" download>Save & Download</a>
JS:
this.downloadJPEGClickHandler = function() {
CollageCore.downloadJPEG(function(data){
$("#controlDownloadJPEG").attr("href", "../file/fileStore.action?fileName=/" + data[0].AttachmentUrl);
});;
return true;
};
The href is getting changed on click, but the link itself is linking to the href set before my JavaScript executes. The first click does nothing as there is no default href and the second click will download what the first click should have downloaded.
I have seen suggestions to use JavaScript window.href instead of relying on the html tag itself. The reason I need to use the html tag is for its download functionality.
You are treating an asynchronous call as it it is synchronous. It is like ordering a delivery pizza and expecting it to be there as soon as you place the order. That does not happen unless you are standing in the restaurant and it is already been made.
You need to cancel the click and fire the page change manually when the call comes back. So you want to use window.location.href = "new path"; instead of setting the href.
this.downloadJPEGClickHandler = function() {
CollageCore.downloadJPEG(function(data){
window.location.href = "../file/fileStore.action?fileName=/" + data[0].AttachmentUrl;
});
return false; //or preventDefault if you pass in event object
};
If you are are attaching this activity to an onClick(event) handler you should be able to stop the redirect by passing in event.preventDefault();
cite: http://api.jquery.com/event.preventdefault/
Prevent the default click behavior, change the href attribute, and then imitate the click. Should work.
$( "a" ).click(function( event ) {
event.preventDefault();
$("#controlDownloadJPEG").attr("href", "../file/fileStore.action?fileName=/" + data[0].AttachmentUrl);
$(this).click();
});

Event click on href <a> tag [duplicate]

This question already has answers here:
How do I programmatically click a link with javascript?
(12 answers)
Closed 8 years ago.
I have a question about Javascript event here. I have an <a> tag like this:
<a id='aTag' href='http://example.com'>Click to redirect</a>
Then I call an event like:
<script>
$('#aTag').click();
//or
$('#aTag').trigger('click');
</script>
It does not redirect me to http://example.com. I tried to add an onClick() event in the <a> tag like this:
<a id='aTag' href='http://example.com' onclick='alert("Event happened");'>Click to redirect</a>
And then call the .click() event. It shows me alert("Event happened");
Can anyone show me how to call the .click() event correctly, or correct this redirect with issue with the href in that <a> tag?
In my business I just need an <a> tag, so not with the window.open or windown.location.
Explanation
Redirects can only happen if the user clicks directly on the link. Programmatic or deferred click triggers do not work.
An alternative would be:
to change directly the window.location
to open the link in a new tab/window
Changing window.location
window.location="http://wherever.you/want/to/g0";
or
window.location=$('a.selector').attr('href'); // to use a link's address
New tab/window
You cannot programmatically (click() or trigger) open new tabs/ windows or redirect. They get (ad-)blocked. automatically
So new tab/window openings always have to be triggered by user action. (Otherwise we'd always be full with popup ads)
So 1st of all, make sure that your js is executed on a user event, and then you should be able to use window.open.
JsFiddle example
html:
new tab google
<button class="user">user triggered</button>
<button class="programatic">programatic</button>
js:
$('a').on('click', function(e) {
console.log('clicked', e);
// unfortunately although we simulated
// the click on the <a/> , it will still
// not launch a new window - idk why.
// therefore we can use the line below
// to open the <a>'s href in a new tab/window
// NOTE: this will only occur if the execution was
// triggered by the user
window.open(e.currentTarget.href);
});
var simulateClick = function(origEv) {
var e = $.Event("click");
e.ctrlKey = true;
e.metaKey = true;
e.originalEvent = origEv;
$('a').trigger(e);
};
$('button.user').on('click', function(e) {
// this call will actually open a window
simulateClick(e);
});
$('button.programatic').on('click', function(e) {
// this will result in a blocked popup
$.get('/someurl').always(function() {
// executes the method after a non-user event
// results in blocked popup
simulateClick(e);
});
});
// this will result in a blocked popup
setTimeout(simulateClick, 1000);
Try this -
<a id="aTag" href="http://mylink.com" onclick="return doWork();">Click to redirect</a>
<script>
function doWork(){
//... do your works
return true; // then return true to redirect
}
</script>
Here is the fiddle - http://jsfiddle.net/gcJ73/
(Though the fiddle attributes are a little different to show you that it works)
or with jQuery:
//first assign the click handler
$('#aTag').click(function(){
//... do your work
return true;
});
//then call programmatically
$("#aTag").click(); or $("#aTag").trigger("click");
BTW programatically calling it will not redirect. Will just call the event handler, not redirect.
jQuery fiddle - http://jsfiddle.net/gcJ73/3/
Try:
<script>
jQuery('#aTag').click(function() {
// Your Code
});
</script>
jQuery('#aTag').click() does not execute the href attribute of an anchor tag so you will not be redirected, do:
$(document).ready(function() {
jQuery('#aTag').click( function (e) {
window.location.href = this.href;
});
});
<a id='aTag' href='http://mylink.com' onclick="location.href='http://mylink.com';">
Click to redirect
</a>
check this code snippet, also it will work like what you want to do.

Jquery .click hide function for closing window

I prepared fragment of my page to show you my problem:
a link
On the bottom is show small red window named div "pomocnik"
In Chrome browser click on the "close" icon do it works, but IE does the work prepared for clicking in the text inside DIV
onclick="document.location.href('http://www.google.com')
so it open new page.
IE has detected onclick for DIV but Chrome detected more in detail for image.
My idea is to close window after clicking on close button.
$('#close').click(function() {
//var g = document.getElementById("pomocnik");
//g.style.display = 'none';
$('#pomocnik').hide(2000);
$('#konsul').click = null;
});
I think that the problem is that the event (click onto close image) first calls the event handler which hides your div, but then bubbles up to the containing div and starts the default action for it (open the link). Try the following:
$('#close').click(function(e) {
//var g= document.getElementById("pomocnik");
//g.style.display= 'none';
e.stopPropagation(); //this will prevent the event from bubbling up to the containing div
$('#pomocnik').hide(2000);
//$('#konsul').click=null;
});

href links only open on "right click in new tab"

I'm having trouble with some script interfering with my basic href links and not allowing them to open on left click.
My url is http://www.mayabdesign.com, and on each specific project page (like http://www.mayabdesign.com/#cbp=ajax/sculptjax.html) the "view the site" button does nothing unless you right click and open in a new tab. I know the problem, but can't seem to figure out the solution.
Thanks in advance. :)
Add click function to Dom Ready
$(document).ready(function(){
$("a").click(function( event ) {
if ( $(this).attr("href").match("#") ) {
event.preventDefault();
var href = $(this).attr('href').replace('#', '')
scrollToAnchor( href );
});
});
CHECK DEMO HERE
I think the click events are blocked somewhere with event.preventDefault()
This is the relevent code that is preventing the link from returning. Since the href value does in fact math # its default action is prevented
$("a").click(function( event ) {
if ( $(this).attr("href").match("#") ) {
event.preventDefault();
var href = $(this).attr('href').replace('#', '')
scrollToAnchor( href );
});

clicking link in javascript

I have an anchor tag on all my pages.
<a id='signout' href='//somelocation'>SignOut</a>
and I have a javascript file that is available to all pages. There is a function that is called and attached to 'click' , 'touch' and 'key press' handler where I am trying to click the link. Something like
document.addEventListener('click' function(e){
var signoff = document.getElementById('signout');
location = signoff.href;
}
This should just click the anchor tag whenever there is a click event but is not working.
Some syntax corrections got it working for me:
document.addEventListener('click', function(e) {
var signoff = document.getElementById('signout');
location = signoff.href;
});
http://jsfiddle.net/jjGeJ/

Categories