What does the following code mean -
some link
My basic doubt is which script is run when we click on the link
The onclick will run first. If onclick doesn't return false (in this case it doesn't), then href will be processed.
The javascript part in the href attribute is the protocol (you know, like http, ftp or mailto). What it does is it tells the browser that the URL is actually JavaScript code.
Normally, when you click on a link, the browser will execute whatever it finds in the href attribute. However, the browser will also trigger the onclick event before it handles the href thing. So, setting an onclick handler will override the normal behavior.
Thus, the event handler becomes king and it has the possibility to allow or prevent the default browser behavior by returning true (allow) or false (prevent).
So, in your example, when you click on that link, the browser will trigger addItem. If it returns false, nothing happens. If it returns true, the browser will execute the code in the href attribute. But since it finds no statement in there (i.e. empty statement), nothing happens.
Try the following code:
won't go to google.com
will go to google.com
Does that make sense to you?
Note that when the browser interprets the "javascript:" value of an "href", if the return value is not empty then it is interpreted as the document content desired for the <a> tag! Here is a test page for you to enjoy:
http://gutfullofbeer.net/jslink.html
The source for that page (look at it; it's really short) includes the following link:
<a href='javascript:getLink()'>Click to go there!</a>
The function "getLink()" is defined as follows:
function getLink() {
var sel = document.getElementById('sel');
return sel.options[sel.selectedIndex].value;
}
As you see, the function grabs the current selected value of the <select> element on the page and returns that. What does the <select> element look like?
<select id='sel'>
<option value='<html><head><meta http-equiv="refresh" content="2;http://cnn.com"/></head><body>Redirecting to CNN ...</body></html>'>CNN</option>
<option value='<html><head><meta http-equiv="refresh" content="2;http://zombo.com"/><head><body>Redirecting to Zombocom ...</body></html>'>Zombocom</option>
<option value='<html><head><meta http-equiv="refresh" content="2;http://reddit.com"/></head><body>Redirecting to Reddit ...</body></html>'>Reddit</option>
</select>
The values of those options are complete HTML markup for a page with a redirect to the requested site. Because the URL returns a value, that value is understood by the browser to be the new page content.
It's pretty mind-blowing. I'm not sure why you'd ever do this.
your doubt is true !, you must find "function addItem(x)" in a javascript file that linked by script tag from the page.(usually in head tag)
The "javascript:" inside href is a way to tell the browser to execute javascript instead of going to a different page.
This line, for example will show a message box with "testing" message.
Click me
and this one will execute an empty javascript statement that will do nothing
Click me
The onclick is an event that also fires when a link is clicked. In contrast to href it does not allow you to put in a link to a different page; it accepts only javascript.
Browsers will first fire onclick event and then process href attribute. If it's an URL (empty href means current URL; click will just refresh the page) it will follow it, if it's javascript it will execute it.
Putting "javascript:;" or "javascript:void(null);" inside href is old and wrong technique to ensure browser does not not refresh the page after onclick is processed.
To answer your question; both scripts will execute, but the href script will do nothing.
Related
I'm working on a web application which is a traditional aspx (asp.net) web forms app but has had some angular 6 apps incorporated into it.
I've been tasked with fixing a bug that causes the browser to refresh when clicking on an anchor element with a href="#".
I'm not sure what's causing the whole page to reload.
Strangely when I open dev tools in Chrome, choose the network tab and select disable cache the page only refreshes the first time I click a link and any other subsequent clicks work fine. This might be to do with the fact that after the first time I click it the browser url now contains the # at the end of it.
I know this seems a bit random but I wondered whether anyone had any theories on what may cause the reload in the first place.
It's hard to tell what could be causing this without seeing any code. The most common solution I've used when I get this behavior is a prevent default. You can do something like
<a href="#" (click)="$event.preventDefault()">
Or if you already have a click event then pass in $event as a parameter to your function then preventDefault in the function you are calling. This would look like:
Html
<a href="#" (click)="someFunc($event)">
and in your ts:
someFunc(event) {
event.preventDefault();
// rest of your code here
}
This answer is related to the question and it's the first one that comes up in Google so I hope this is useful.
I have some external web components that use regular anchor tags with hrefs that point to routes in my angular app. Clicking the href causes a full page reload. This is because I'm not using routerLink - but, in my case, I can't.
So, my work around is:
#HostListener('window:click', ['$event'])
onClick(e: any) {
const path = e.composedPath() as Array<any>;
const firstAnchor = path.find(p => p.tagName.toLowerCase() === 'a');
if (firstAnchor && !firstAnchor.hasAttribute('routerlink')) {
const href = firstAnchor.getAttribute('href');
this.router.navigateByUrl(href);
e.preventDefault();
}
}
Depending on your application, you might need to make some other checks e.g. is the target _blank, is it an external url etc.
change your a tag code as below
A Tag
this will invoke yourClickEvent(); without page reload
check the stackblitz here stackblitz
If you don't want to reload the page use $event.preventDefault()
<a href="#" (click)="$event.preventDefault()">
Try using debug tools to select the element, then click Event Listeners and then the Click event to see what is listening. Perhaps you can track it down that way.
You could also simply paste this into the console to trigger a break, and then click any of the offending elements:
['unload', 'beforeunload'].forEach(function (evName) {
window.addEventListener(evName, function () {
debugger; // Chance to check everything right before the redirect occurs
});
});
source: Break when window.location changes?
As you are using angular routes, try to use this notation:
<a [routerLink]="['./']" fragment="Test">
As explain by this comment: https://stackoverflow.com/a/38159597/4916355
use href="javascript:void(0);"
The reason you’d want to do this with the href of a link is that normally, a javascript: URL will redirect the browser to a plain text version of the result of evaluating that JavaScript. But if the result is undefined, then the browser stays on the same page. void(0) is just a short and simple script that evaluates to undefined.
Use [routerLink] instead of using href = "", and use click event to call your calling method in the typescript file.
ex:
// downloading the file based on file name
<a [routerLink]="'file://' + 'path'" (click)="downloadFile(templateDocument.fileName)">{{downloadDocuments.fileName}}</a>
Since you have mentioned the web app is asp.net webforms, can you please let us know
Whether the link is asp.net hyperlink control. If so,
AutoEventWireUp could cause the link to be automatically submitted:
Please have a look at this link
If you do have asp.net server controls on the page, then you could disable by setting
#Page AutoEventWireup="false"
For the entire project, this can be disabled by setting in web.config:
I have a simple javascript program that runs onclick of an image.
However, whenever I clicked the image, the page reloaded.
After a lot of debugging I found that the page doesn't reload until right as the script completes.
There are several setTimeouts in the code, but I noticed the page was reloading instantly. I even changed these timeouts to 15000 milliseconds, but it still reloads immediately.
I am using jquery, if it makes any difference.
I also want a different result from the program every time you click it, so that each time you click it a different script runs and a some text changes in a specific order. I did this by changing the onclick attribute of the images in each script to the name of the next script, so that script one would switch onclick to script two, and so on. I set a timeout on these switches so that one click doesn't race through every single script. script two isn't running, so that much works.
my code:
function getSounds() {
console.log("script. initiated");
$("#soundwebGetSoundDirections").html("Now, Wait until the file is done downloading and click below again.");
console.log("new message");
$("#soundwebGetSoundA").attr('href',"");
console.log("href eliminated");
setTimeout($("#soundwebGetSoundImg").attr('onclick','findFile()'),2000);
console.log("onclick to findFile()");
}
function findFile(){
console.log("FINDFILE")
$("#soundwebGetSoundDirections").html("Find the file(it's probably in your downloads), copy the path of the file (usually at the top of the file explorer) and paste in it the box below. Then, make sure there is a '/' at the end of the path and type 'Linkiness.txt' (case sensitive, without quotes) at the end. Once you have all that stuff typed, click the icon again.");
console.log("FIND IT, DARN IT!!");
$("#soundwebGetSoundPathInput").css("opacity",1);
console.log("diving into reader");
setTimeout($("#soundwebGetSoundImg").attr('onclick','readFile()'),1000);
}
function readFile(){
console.log("loading...");
$("#soundwebGetSoundDirections").html("loading...");
if(document.getElementById("soundwebGetSoundPathInput").value.length == 0){
setTimeout($("#soundwebGetSoundDirections").html("Please fill in Path!"),1000);
setTimeout(findFile(),2000);
}
}
and the HTML that's linked to,
<a id = "soundwebGetSoundA" href = "https://docs.google.com/feeds/download/documents/export/Export?id=1ynhHZihlL241FNZEar6ibzEdhHcWJ1qXKaxMUKM-DpE&exportFormat=txt">
<img onclick = "getSounds();" class = "soundwebImgResize" src = "https://cdn3.iconfinder.com/data/icons/glypho-music-and-sound/64/music-note-sound-circle-512.png" id = "soundwebGetSoundImg"/>
</a>
Thanks for any help,
Lucas N.
If you don't want clicking the image to cause the anchor tag to load the href, then move the image tag outside of the anchor tag.
You aren't using setTimeout correctly. You should be passing in a function not a statement. So, for example, instead of
setTimeout($("#soundwebGetSoundDirections").html("Please fill in Path!"),1000);
setTimeout(findFile(),2000);
you should use
setTimeout(function () { $("#soundwebGetSoundDirections").html("Please fill in Path!") },1000);
setTimeout(findFile,2000);
I think the same goes for setting the onclick attribute but I've never tried dynamically changing an onclick attribute like that.
Since you're already using jQuery you could try using .on('click'... and .off('click'... if your current setup isn't working.
I have a collection of anchor tags, which look like so:
<a href='#123'></a>
I use the #123 as an id, which I supply to an AJAX call. I make the call on click of a link. After a link is clicked, besides the displaying of the results of the AJAX call, two things happen:
the url in the address bar gets the hash like so: www.localhost.com/foo#123.
The href attribute of the clicked link gets changed from #123 to the AJAX address www.localhost.com/bar#123. If I don't make an AJAX call (for test purposes), then it changes to the current url in the address bar: www.localhost.com/foo#123.
If I use event.preventDefault, than both of these things don't happen. I want to keep 1. (changing of the hash value in the address bar), but I don't won't to keep the value of the href, as otherwise, a subsequent click on the same link results in an error.
How can I do this?
My code
I will include a simplified version of my code, which still produces the same effect.
makeAjaxCall = (brandId) ->
alert 'OK'
$ ->
$('.box-trigger').on 'click', (e) ->
makeAjaxCall($(this).attr('href'))
This code gets loaded on page www.localhost.com/foo. If I click on the link, than I gen an alert with 'OK', the address changes to www.localhost.com/foo#123 and the href of the link also changes to www.localhost.com/foo#123.
Clarification regarding foo and bar
In the makeAjaxCall function, if I really make an ajax call to the url www.localhost.com/bar, then the href changes to www.localhost.com/bar#123. However, I removed the Ajax call to try to debug the problem. In that case the href changes to the current url, in this case www.localhost.com/foo#123.
Solution
I ended up using event.prevenDefault + manually appending the hash to the address bar url like so:
$ ->
$('.lightbox-trigger').on 'click', (e) ->
e.preventDefault()
makeAjaxCall $(this).attr('href')
window.location.hash = $(this).attr('href')
Solution suggestion 1
I would use the data parameter, as suggested by Optimus in the comments. Like this:
HTML
<a class="box-trigger" data-id="#123"></a>
Note: I don't have the href parameter at all, this is because we don't want the URL to be affected at all, right? It's an AJAX call after all. (This will, however make most browsers not recognise the <a> tag as a link. It will lose its "link styling" as it where. You can easily simulate this by simply styling it using CSS.)
CoffeeScript
makeAjaxCall = (brandId) ->
alert 'OK'
$ ->
$('.box-trigger').on 'click', (e) ->
makeAjaxCall($(this).data('id'))
Note: I have never used CoffeeScript, so this is just a guess.
Solution suggestion 2
If you, for some reason wish to have the ID as an anchor inside the href, you could have a look at the JQuery event.preventDefault() function. This might just stop the URL from changing and all other behaviour you're experiencing.
I currently making a filebrowser. If the user clicks on a link to a file a little window open and asks for options (like download and view). I've done this using the onclick attribute. If I click on the link the javascript is executed, but after this the url specified in href opens. What I'm trying to do is: If you click the link javascript get executed and forwards you eventually. But if the link gets rightclicked the "copy link location" should still be available.
I'm thinking of solving this by blocking the forwarding scriptside. So if the link gets rightclicked no javascript is executed and you can copy the link location. But if you left click the link the javascript is executed and the link is not opened.
Is that possible with javascript, or is there any other way of achieving this behavior?
In order to prevent the link executing, one way is to let the "onclick" method return false.
For example:
...
If clickfunc() returns false, a click on the link will not direct to "http://..."
Although you are probably handling it more like
...
<script>
document.getElementById('somebutton').onclick = function() {
...
else { return false; }
};
</script>
You have to prevent default from your click function:
function stopDefAction(evt) {
evt.preventDefault();
}
Yes, you will need to prevent the default action of the event. You can do so by returning false in your onclick attribute.
you can replace href attribute by text "javascript:void(0)", for example:
...
<script>
document.getElementById('somebutton').href="javascript:void(0)"
</script>
Can we use 2 different url on same for javascript disabled and enabled condition
If javascript is enabled then link should be <a href="link1">
and If javascript is disabled then link should be <a href="link2">
You could set the JS disabled URL in the markup, then on page load use JS to replace the url with the enabled URL.
HTML:
<a id="id" href="js_disabled_url" />Link</a>
jQuery example:
$(function() {
$('#id').attr('href','js_enabled_url');
});
This should degrade gracefully.
Yes, just write a JavaScript which finds the element you want to change the href of when the page has loaded.
Example using JQuery:
$(function () {
$('a.changeable').each(function () {
$(this).attr('href', 'http://google.com/lol');
});
});
(Untested, but you get the idea.)
So basically, if the user has disabled JavaScript, the default link is used, otherwise the new URL given by the script is used. So your HTML should contain the link that should be used when JavaScript is disabled.
If I understand you correctly, you can have one url on the html page, and if javascript is working, have the javascript change the url on the anchor.
That way you can ensure that the second url only works if javascript is enabled.
The problem is that if javascript was enabled when the page was loaded, and later disabled then you won't know.
But, if you just have an onclick on the anchor, then you can change the url when it is clicked on, then it will always work correctly, as, if they disable javascript after the page is loaded it will still go to the non-javascript url, and if the onclick works then it will go to the other url.