<html>
<body>
<a href="javascript:helloWorld()" >Hello world</a>
<script type="text/javascript">
function helloWorld(){
console.log("Hello world");
return true;
}
</script>
</body>
</html>
If open this page in firefox(not happening in chrome) and click on the link, I will get back new empty page, with "true" as a content. Why is this happening? Is this a expected behaviour or a bug. Although I was able to fix it by replacing it with helloWorld();void(0);.
This is expected behaviour.
The javascript: URL scheme is designed so you can generate content from JavaScript and have it rendered as a new page.
Using it to trigger effects on the current page is a hack.
If you want to trigger events on the current page then use a click event listener instead (and use a button instead of a link if you aren't going to have a fail-state of "visiting another page").
When the browser navigates to a javascript: URI, the code is evaluated and it's return value (the return value of the last expression) is used: If it's undefined, the the browser doesn't navigate, else the browser navigates to a page with the content of the conversion of that value to a string.
Since helloWorld() returns true and it's the last expression in your code, the browser creates a page with "true" as its content. void(0) returns undefined, so it doesn't navigate.
I recommend not using hyperlinks for triggering actions. That's not what they were made for. From the HTML standard:
[Hyperlinks] are links to other resources that are generally exposed to the user by the user agent so that the user can cause the user agent to navigate to those resources, e.g. to visit them in a browser or download them.
That's not what you're doing. Use the <button> element instead and style it like a link.
Related
I need to add a second click event to a link. I would like to add a modal event like shown in this codepen - but it already uses the HREF for the download link. What is the best way to handle this?
<a download href="/path-to-file"><strong>DOWNLOAD</strong></a>
To be clear. I need the link to file to stay as is but also trigger the popup.
An <a> element can trigger functionality on its way to its href (target). It has a built-in HTML property (global event handler, to be specific), called onclick, that's common across most HTML content elements.
The onclick handler will be performed first. It takes an attribute (named event), which is the PointerEvent.
So this will work:
<script lang="javascript">
function doSomething(e) {
console.log(`You clicked <${e.target.localName}>`);
debugger;
// Press F8 to resume execution
}
</script>
<a download href="/path-to-file" onclick="doSomething(event)"><strong>DOWNLOAD</strong></a>
The click pointer event bubbles. Which means once the onclick handler bound on the element has been executed, the document looks for any other onclick handlers bound on its ancestors (parent elements). If it finds them, it executes them as well, in order (closest first), all the way up to document (which contains <body>, as .body).
What this means is that you don't necessarily have to bind your onclick handler onto the element with the href itself. You can bind it on any of its parents and it will still be performed before the document goes to the <a>'s href:
<script lang="javascript">
function doSomething(e) {
console.log(`You clicked <${e.target.localName}>`);
// uncomment next line to stop it getting to href (and see the log above)
// e.preventDefault();
}
</script>
<div onclick="doSomething(event)">
<a download href="/path-to-file"><strong>DOWNLOAD</strong></a>
</div>
You can call .preventDefault() on the event to stop it from going to href and from bubbling.
To stop it from bubbling but still allow it to go to its href you can call .stopPropagation() on it.
Note: throughout my answer I used links to the MDN web docs. Instead, I could (some might even say should) have used links to the actual HTML Living Standard (a.k.a. "official HTML documentation"). I chose not to, because most people find the Standard too technical, therefore harder to digest. But note every MDN page has a link to the official documentation for that resource at the bottom of the page.
I have just read some concept about window.location property and method.
And I know that
1. window.location.href = "http://google.com"
2. window.location.assign("http://google.com")
3. window.location.replace("http://google.com")
are all can redirect our page to the target url, the only difference is that window.location.replace doesn't record the history, so we cannot get back to the previous page directly.
Now I just wondering, what's is the difference between window.location.href and Google, the <a> tag also records the history.
And for what situation do we use them respectively?
I think the main difference is what's happening behind the scene but on the surface they are pretty much giving the same effect.
window.location.href is only triggerable by JavaScript, or in JS context. Whereas a <a> tag defines hyperlink in HTML. It really depends on how you want to trigger this new page. You can either have a hyperlink a user can click/tap on, or you can trigger the page load by some JS functions that are triggered by certain actions.
To be more specific, a tag is common in webpages because browsers understand it and can apply CSS style to it to look nicer. As for window.location.href, there's no UI aspect for it, it simply is a line of JS code that you can trigger to either (1) get the current webpage URL or (2) set a value to it to redirect the user to some other URLs.
The difference is in how they are likely to be used (duh, bear with me.)
Setting window.location.href is a way to programmatically set the URL. For instance, window.location.href = 'https://www.google.com' will navigate the user to Google's search page. There is no way for your user to make use of this knowledge, unless they open the developer console.
Using an anchor tag of Google will show a hyperlink that the user can click, navigating them to Google's search page. This tag is also more likely to be interpreted by a screen reader more appropriately than a button with an onclick that navigates them to Google by setting window.location.href manually in Javascript.
I want to perform two tasks on click on a single link. For example, clicking on an coupon link should take the user to the merchant's website on a new page and the page where the link was clicked should display the coupon code. This is similar to what happens in Coupondunia etc...
Right now I have a single link, if I click it, it opens a new page, but does not perform the second action that I mentioned earlier, could you please provide me any insights?
I am using ASP.net MVC
TestLink
You have to use JavaScript for this. With straight HTML clicking a link will only perform one action: issuing a GET request to the specified URL. To pop your dialog, you need only add an event handler to the link's click event that will show that dialog. Something along the lines of:
$('#MyLink').on('click', function () {
// show dialog
});
The default action, requesting the URL, will happen regardless, unless you stop it with either evt.preventDefault() or by returning false. As a result, you don't need to add anything special in that regard.
However, bear in mind, that unless the link has a target attribute, it will load in the same browser tab/window, meaning that by the time your dialog displays, the entire page view would have changed to the new URL. As a result, you should ensure that the link opens in a new tab/window, by adding target="_blank" (or a more specific target) to your anchor tag.
#alok...hey brother...are u asking for something like this ...that i mentioned below...let me know...if it is what you are asking for or not...
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>DemoButton</title>
</head>
<body>
<input id ="Demo_Btn" type="button" value="click" onclick="test1(), test2()"/>
<script type="text/javascript">
function test1() {
//define your test1 here...
}
function test2() {
//define your test2 here...
}
</script>
I have a group of links on a page. when the user clicks a link it triggers an asynchronous request and a content area on the page is updated with the response html.
This works fine, except for if the user clicks the link with the 'middle-button' (or mouse wheel, whatever it's called!). Then a new tab opens and the response gets returned and rendered to that tab.
Is there any way for me to prevent this from happening?
catch the link with javascript and override the default link behaviour.
like this:
$('a.ajax').click(function(e){
e.preventDefault();
// do ajax stuff, and add an onfinish function that does
// something like document.location.href = this.attr('href');
});
You don't have to do the document.location.href, as I just noticed that a content area is updated. Just catch the default behaviour with the e.preventDefault();
// edit
The preventDefault won't stop the middle mouse button... Have you considered not using tags? I know it should be accessible so maybe a span containing the link, so you can add the onclick event on the span and hide the link with css?
Unfortunately no, Javascript wont have access to that sort of control for security reasons as it would be wide open for abuse.
I'm trying to focus an existing tab when the content reloads. The usual window methods don't seem to work.
Here's whats happening: On page_1 I have a link like...
Go to my other page
If the tab doesn't exist, when the link is clicked it opens a new tab and takes focus. (Perfect)
If you then go back to page_1 and click the link again, it reloads the content in the existing tab (perfect) but doesn't focus (crap). I've tried the usual window.focus, $(window).focus methods on load with page_2 without luck.
Any recommendations?
It is impossible.
The following appears to work in IE8 and FF13:
<script type="text/javascript">
// Stupid script to force focus to an existing tab when the link is clicked.
// And yes, we do need to open it twice.
function openHelp(a) {
var tab = window.open(a.href, a.target);
tab.close();
tab = window.open(a.href, a.target);
return false;
}
</script>
Help
There is a workaround to this. Use javascript to open a window in a new tab, store a reference to that tab, and when you want to focus it; close it first and then re-open it.
if (window.existingWindow != null)
try { window.existingWindow.close(); } catch (e) { };
window.existingWindow = window.open("/your/url", "yourTabName");
We use a similar approach to opening the preview pane of the current page you're working on in our service called Handcraft where the above works as expected (we wanted the new window to always focus).
Without using a framework you can put a script block at the bottom of your page that will run once the page loads. Because it is after your HTML you can be assured that the HTML is refers to is actually available.
The script can set the focus to the element you want.