My links are javascript functions which show a loader, then navigate to the target link:
<script>
function go(url) {
document.body.innerHTML = "some loader html";
window.location = url;
}
</script>
Click here
However this link wouldn't work when the user right clicks it and wants to navigate to test.php in a new tab.
I want the link also to function when the user wants to open it in a new tab/window. Is there a javascript/jquery way I can achieve this?
Thanks
Your links should be links, not JavaScript functions. Their primary purpose is navigation. You can add the extra behavior later, in a click handler:
document.body.addEventListener('click', evt => {
const link = evt.target.closest('a.use-loader');
if (!link) return;
evt.preventDefault();
document.body.innerHTML = '<h1 style="color:red">LOADING</h1>';
window.location.href = link.href;
});
<a href="https://example.com" class="use-loader">
This loads <em>really slow</em>, and it's my responsibility to fix that.
</a>
<br>
This one, too.
Or with jQuery:
$('body').on('click', 'a.use-loader', function () {
document.body.innerHTML = '<h1 style="color:red">LOADING</h1>';
window.location.href = $(this).attr('href');
return false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="https://example.com" class="use-loader">
This loads <em>really slow</em>, and it's my responsibility to fix that.
</a>
<br>
This one, too.
This way, the links still work for any agent that isn't running JavaScript, including browsers opening new tabs and users running NoScript.
Firstly, "My links are javascript functions which show a loader, then navigate to the target link" sounds like bad design decision.
To answer your question...
window.open('test.php', '_blank');
the second parameter will be the name of the target window
see How to simulate target="_blank" in JavaScript
The only way to get a right click 'open in a new window' is to have your tag like this
Click here
I highly recommend that you do not open the link using javascript, this is usally bad practice and you will most likely run into popup blocker issues.
I would do this personally
Click here
Maybe this "loader" you want to show is supposed to imitate an AJAX loading approach where you load new HTML and insert it into your page without causing an actual page reload
you might be interested in this
How do I load the ajax data into a div with jquery?
Related
I have a website-1 (www.example.com). When a customer reaches out to my website, the other website-2 (www.example2.com) should be open in a new tab corresponding with the website (www.example.com).
How to do this
I would like to add to Daan Teppema's answer.
Add rel property in the tag, if the website is not safe or untrusted add noopener. but if you are directing within your website remove the noreferrer for SEO tracking purposes.
Example 2
This will keep your website tab open and in the meantime open a new tab with the link you've provided.
You can do an <a> element with the target="_blank" attribute.
Like so:
Example 2
If you want them both to load, then you can make it go to the second one in another tab with javascript using the window.onload event.
Like so:
window.onload = function() {
window.open(url, '_blank').focus();
};
Basically, I have a page with social media share buttons. Some of them work as they should (they open up in a new window), however, others open up both in a new window and in the same window. I have been going crazy for a day now over this and I cannot seem to find a way to fix it.
For reference, this is the page: http://www.inetsolutions.org/gsa-search-engine-ranker-ultimate-tutorial-and-genuine-review-seo-software-of-the-gods/
Link that works as expected (Facebook, Twitter, Pinterest):
<a href="javascript:void(0)" class="ism_link" onclick="indeedPinterestPopUp(2513);ism_fake_increment('.pinterest_share_count', 'pinterest', 'http://www.inetsolutions.org/gsa-search-engine-ranker-ultimate-tutorial-and-genuine-review-seo-software-of-the-gods/');">
Link that opens the URL to share in both a new window and in the same:
<a href="http://www.stumbleupon.com/badge/?url=http://www.inetsolutions.org/gsa-search-engine-ranker-ultimate-tutorial-and-genuine-review-seo-software-of-the-gods/&title=GSA%20Search%20Engine%20Ranker%20Ultimate%20Tutorial%20and%20Genuine%20Review%20%E2%80%93%20SEO%20Software%20of%20the%20Gods" class="ism_link" onclick="ism_fake_increment('.stumbleupon_share_count', 'stumbleupon', 'http://www.inetsolutions.org/gsa-search-engine-ranker-ultimate-tutorial-and-genuine-review-seo-software-of-the-gods/');return !window.open(this.href, '', 'width=700,height=575');">
What I have tried:
I have tried to remove the "href" attribute of the tag and insert the URL string into the window.open function instead of using "this.href". When I do that, the link opens only a new window, but doesn't open the share page of the respective social media, but rather, the target URL.
I have tried to add "return false" after the non-working window.open function.
I have also tried to remove the "ism_fake_increment" function just to test, but again, to no avail.
I have contacted the plugin author, but they requested to access my website internally, which is not going to happen.
Any ideas will be strongly appreciated. Thank you for your time!
I advise that you don't use the onclick attribute because it leads to extremely messy code. Instead, use the .addEventListener() in the DOM.
To disable the link from opening the link in the same window, just disable the default even. This can be done with .addEventListener() in the callback by calling the .preventDefault() method of the object passed into the callback:
//Get our link:
var link = document.getElementById("stumbleupon");
//Bind the click event:
link.addEventListener("click", function(event) {
//Prevent the link from opening regularly with .preventDefault():
event.preventDefault();
//The following code with the plugin does not work because we haven't included the plugin in the code snippet, but as you can clearly see if you click the link, the link has clearly been disabled because of the above call to .preventDefault().
//Do different stuff with the plugin:
ism_fake_increment('.stumbleupon_share_count', 'stumbleupon', 'http://www.inetsolutions.org/gsa-search-engine-ranker-ultimate-tutorial-and-genuine-review-seo-software-of-the-gods/');
return !window.open(this.href, '', 'width=700,height=575');
});
<!-- Set the ID attribute so we can find this link in the DOM: -->
<a id="stumbleupon" href="http://www.stumbleupon.com/badge/?url=http://www.inetsolutions.org/gsa-search-engine-ranker-ultimate-tutorial-and-genuine-review-seo-software-of-the-gods/&title=GSA%20Search%20Engine%20Ranker%20Ultimate%20Tutorial%20and%20Genuine%20Review%20%E2%80%93%20SEO%20Software%20of%20the%20Gods" class="ism_link">Hello! This is a link to stumbleupon.com!</a>
I am working on a JS program which should open a webpage www.mysite.com & click on a link inside that webpage to download a pdf.
The link to click looks like this:
<a onclick="download();return false;" href="#noWhere">Click to Download</a>
Ordinarily, manually clicking the link, calls the following function to download the pdf:
function download() {
document.forms[0].action = path + "/xxW04_sv_0140Action.do";
document.forms[0].target = "_self";
document.forms[0].submit();
}
My code is simplified javascript code to open the page & click on the "Click to Download" button is this:
<script>
var linkname = "http://www.mysite.com";
var windowname = "window_1"
// Opens a new window
var myWindow = window.open(linkname, windowname ,"width=400,height=600");
//should open a link to download pdf
myWindow.document.getElementById('href = \"#noWhere\"').click();
</script>
So far I can open the webpage "mysite.com" in a seperate window using but for some reason no button clicking is happening and certainly no pdf is downloaded.
Of course if I manually click the "Click to Download" button it downloads.
Can anyone tell me what i'm doing wrong? Why I cannot simulate a click with the above js code?
Or possibly give me some things to try. Any help much appreciated and Than you.
UPDATE:
From the initial answers below, possibly this method is doomed for failure! Can anyone suggest a better way I could be downloading these pdfs?
You'd better use:
<a href="http://www.mysite.com/mypdf.pdf">
This should download that pdf file.
It won't work. The same-origin policy will prevent you from accessing the content of any pages loaded from another domain.
Also, as #kamilkp pointed out, you have to provide the getElementById() function with an id value. You can't just plug any old stuff in there and expect it to work.
Another problem is your reliance on clicks for this to work. What about users that use the tab key to select links and then press Enter to follow the link?
Trying to open a link in a framed page and close the child window. The link bellow is in a child window and when I click it opens the link in the framed page, but did not close the child window
<a target="Resultado" href="?Tela=1"
onClick="javascript:return confirm('TryMe');window.close();">
I have used a code like this to close the window... but couldn't get it to work with the above code.
<a href="javascript:window.opener='Resultado';window.close();">
Try this:
<a target="Resultado" href="?Tela=1" onclick="clickHandler(event, this);">Link</a>
And declare this:
function clickHandler(e, el) {
var choice = confirm('TryMe');
if (!choice) {
e.preventDefault();
}
window.close();
}
I wasn't sure of your original use of window.close() since it came after the return and would never execute, so it's up to you to move it to where you want.
Create another webpage on your webserver & use that as the Custom URL thankyou page for your form.
In that new webpage have just one line of code.
<body onload="javascript:window.opener.childClosed();window.close();">
--
That code will call a javascript function in the parent window and then close the child popup; you can then use that javascript function to do a redirect on your parent page.
I am not to sure where the URL of your 'Thank you for requesting...' page is, but here is some javascript to redirect to google on your parent page after the form is submitted.
function childClosed() {
window.location = "http://www.google.com/"
}
You can put that script before your closing <body> tag.
--
Hopefully I have understood your query OK, let me know if you have any questions or need any clarification on this possible solution.
-
I have made a very basic clone of your webpage & form here if you want to test out the functionality, 'Factoring Question?' is the link that contains this code.
I know that most links should be left up to the end-user to decide how to open, but we can't deny that there are times you almost 'have to' force into a new window (for example to maintain data in a form on the current page).
What I'd like to know is what the consensus is on the 'best' way to open a link in a new browser window.
I know that <a href="url" target="_blank"> is out. I also know that <a href="#" onclick="window.open(url);"> isn't ideal for a variety of reasons. I've also tried to completely replace anchors with something like <span onclick="window.open(url);"> and then style the SPAN to look like a link.
One solution I'm leaning towards is <a href="url" rel="external"> and using JavaScript to set all targets to '_blank' on those anchors marked 'external'.
Are there any other ideas? What's better? I'm looking for the most XHTML-compliant and easiest way to do this.
UPDATE: I say target="_blank" is a no no, because I've read in several places that the target attribute is going to be phased out of XHTML.
I am using the last method you proposed. I add rel="external" or something similar and then use jQuery to iterate through all links and assign them a click handler:
$(document).ready(function() {
$('a[rel*=external]').click(function(){
window.open($(this).attr('href'));
return false;
});
});
I find this the best method because:
it is very clear semantically: you have a link to an external resource
it is standards-compliant
it degrades gracefully (you have a very simple link with regular href attribute)
it still allows user to middle-click the link and open it in new tab if they wish
Why is target="_blank" a bad idea?
It's supposed to do exactly what you want.
edit: (see comments) point taken, but I do think that using javascript to do such a task can lead to having some people quite upset (those who middle click to open on a new window by habit, and those who use a NoScript extension)
Please, don't force opening a link in a new window.
Reasons against it:
It infringes the rule of the least astonishment.
The back-button don't work and the user not possibly knows why.
What happen in tabbed browsers? New tab or new window? And whichever happens, is it what you wants, if you mix tabs and windows?
The reason I always hear in favor of opening a new window is that the user will not leave the site. But be sure, I will never come back to a site that annoys me. And if the site takes away control from me, that is a big annoyance.
A way may be, that you give two links, one is normal, the other opens it in a new window. Add the second with a little symbol after the normal link. This way users of your site stay in control of which link they want to click on.
Here is a plugin I wrote for jQuery
(function($){
$.fn.newWindow = function(options) {
var defaults = {
titleText: 'Link opens in a new window'
};
options = $.extend(defaults, options);
return this.each(function() {
var obj = $(this);
if (options.titleText) {
if (obj.attr('title')) {
var newTitle = obj.attr('title') + ' ('
+ options.titleText + ')';
} else {
var newTitle = options.titleText;
};
obj.attr('title', newTitle);
};
obj.click(function(event) {
event.preventDefault();
var newBlankWindow = window.open(obj.attr('href'), '_blank');
newBlankWindow.focus();
});
});
};
})(jQuery);
Example Usage
$('a[rel=external]').newWindow();
You can also change, or remove the title text, by passing in some options
Example to change title text:
$('a[rel=external]').newWindow( { titleText: 'This is a new window link!' } );
Example to remove it alltogether
$('a[rel=external]').newWindow( { titleText: '' } );
Perhaps I'm misunderstanding something but why don't you want to use target="_blank"? That's the way I would do it. If you're looking for the most compatible, then any sort of JavaScript would be out as you can't be sure that the client has JS enabled.
link text
Details are described in my answer to another question.
<a href="http://www.google.com" onclick="window.open(this.href); return false">
This will still open the link (albeit in the same window) if the user has JS disabled. Otherwise it works exactly like target=blank, and it's easy to use as you just have to append the onclick function (perhaps by using JQuery) to all normal tags.
If you use any flavor of strict doctype or the coming real xhtml-flavors, target isn't allowed ...
Using transitional, whatever being HTML4.01 or XHTML1, you can use Damirs solution, though it fails to implement the windowName-property which is necessary in window.open():
In plain html:
link
If however you use one of the strict doctypes your only way of opening links would be to use this solution without the target-attribute ...
-- by the way, the number of non-js-browsers is often miscalculated, looking up the counters numbers refer very different numbers, and I'm wondering how many of those non-js-browsers is crawlers and the like !-)
If I'm on a form page and clicking on a moreinfo.html link (for example) causes me to lose data unless I open it in a new tab/window, just tell me.
You can trick me in to opening a new tab/window with window.open() or target="_blank", but I might have targets and pop-ups disabled. If JS, targets and pop-ups are required for you to trick me into opening a new window/tab, tell me before I get started on the form.
Or, make links to another page a form request, so that when the visitor submits, the current form data is saved so they can continue from last time, if possible.
I use this...
$(function() {
$("a:not([href^='"+window.location.hostname+"'])").click(function(){
window.open(this.href);
return false;
}).attr("title", "Opens in a new window");
});