mimic a click on a download link using another click - javascript

adown is a link to a file to be downloaded
it works on my page
btndown is a button to mimic adown click
but simply - doesn't work - nothing happens on btndown click
any help
$('#btndown').on('click', function(){
$('#adown').click();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a id='adown' href='test.html' download>down</a>
<button id='btndown'>CLICK</button>

To trigger the click on the a element in order for it to initiate the download you need to fire the event on the Element object, not the jQuery object:
$('#btndown').on('click', function() {
$('#adown')[0].click();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a id="adown" href="test.html" download>down</a>
<button id="btndown">CLICK</button>
Note that I would suggest not using this pattern though, as it's very easily broken by both users disabling JS and by browser updates. I would suggest changing the button to a duplicate <a download> element, styled as necessary if that is the reason behind changing the element type.

Related

Using 'href="#"' needs 2 Back presses in some browsers

I have javascript that uses 'href="#"' to call a function when it's clicked. The problem is that when I run it on Chrome, I need 2 Back presses to return to the referrer page, but on Opera, I only need 1 Back press.
I read the details about using 'href="#"' here:
What is href="#" and why is it used?
here is my test code:
<p>
<script type="text/javascript">
function testOnClick(){
document.write("onClick() support was detected!<br>");
}
</script>
</p>
Clicking on the link should clear the screen and display progress text<br />
<a onclick="testOnClick();" href="#!">
Click here to test onClick
</a>
You might need to use event.preventDefault();
function testOnClick(event) {
event.preventDefault();
document.write("onClick() support was detected!<br>");
}
It prevents your navigator to navigate to the # link, thus, having to press back.
You can also get similar functionality by using a different element and making it look like a link. If you aren't navigating the user to a different section of the page or a new page, for example, you probably should be using the <a> tag.
Here's a fiddle for what I mean: http://jsfiddle.net/2ph2d2gd/
The use case for this would be to open a modal, or do some other action that doesn't necessarily navigate the user anywhere. I don't know your specific circumstances, so you may or may not want to use something like this.
Note: I used alert instead of document.write because jsfiddle doesn't allow the latter.
HTML:
Clicking on the link should clear the screen and display progress text<br />
<span class="link" onclick="testOnClick();">
Click here to test onClick
</span>
CSS:
.link{
text-decoration:underline;
color:blue;
cursor:pointer;
}
Javascript:
function testOnClick(){
alert("onClick() support was detected!");
}
I've had good results leaving the href blank in this scenario. It doesn't reload the page with "#" at the end of the URL and events still fire.
I'm not sure how well that works with JS onclick, but you could replace that with jQuery.
<script type="text/javascript">
$(function() {
$("#link").on("click", function() {
alert("click");
});
});
</script>
<a id="link" href="">
Click here to test onClick
</a>
If you use href="#", make sure onclick always contains return false; at the end, that any called function does not throw an error and if you attach a function dynamically to the onclick property make sure that as well as not throwing an error it returns false.
OR
Use href="javascript:void(0)"
More information about why can be found in this question

Chrome ignoring jquery click function

I have the following html/code that works fine in IE but when I click the link in Chrome, nothing happens.
The HTML is as follows:
<h1 id="pagetitle">Daina - kora dziesmu kr&#257jums</h1>
<div class="frontpage">
<p id="arvilcinu">Ar vilci&#326u R&#299ga braucu</p>
</div>
<!--***************** Ar Vilcinu *******************-->
<div id="arvilcinudisplay" class="singlesong">
<p>Click here to download PDF file for printing</p>
<p>Click here to watch the video - sung by Daina</p>
<p id="back"><img src="backbutton.jpg" alt="Back to Main menu" height="40" width="100"></p>
</div>
The jquery bit of script is as follows:
$("#arvilcinu").click(function(){
$(".frontpage").fadeOut(1000,function(){
document.getElementById("pagetitle").innerHTML = "Ar vilci&#326u R&#299ga braucu";
$("#arvilcinudisplay").css("display","block");
});
});
The idea is that when the user clicks the link (id=arvilcinu) that the link fades out and the relevant info is then displayed. Clicking the link in Chrome just makes the screen flash for a second but nothing on the screen changes.
Thanks
You need to use preventDefault() to remove natural behaviour of link and to fire click event written by you, like below :
Also you can write your code in jQuery only (no javascript) --
$("#arvilcinu").click(function(e){
e.preventDefault();
$(".frontpage").fadeOut(1000,function(){
$("#pagetitle").html("Ar vilci&#326u R&#299ga braucu");
$("#arvilcinudisplay").show();
});
});
Working Demo
It is because of the two event will be occur when you click on the link. one is of your anchor tag <a href="" >... and another is of your click event on element whose id is arvilcinu. anchor tag is inside of the <p id="arvilcinu"> which leads to this behaviour.
You need to prevent default behaviour of the <a> tag which will be done by using
event.preventDefault() function on the event.
If this method is called, the default action of the event will not be triggered.
You code should look like below :
$("#arvilcinu").click(function(e){
e.preventDefault();
// rest of you logic on click event
});

How to send notification when user clicks ad?

I am developing a system that shows advertisements on mobile devices. Our clients are allowed to use their custom HTML code for their advertisement. We would like to be notified when a user clicks this ad. I can wrap the user's code with some of my code. For example:
<div id="my-code" onclick="myFunction()">
<!-- users code -->
click me!
<button onclick="someCode()" />
</div>
As you can see, the user can use javascript within their advertisements. When the ad is clicked I want to notifiy an external server, but I don't want to change the behavior of the ad. I have tried several approaches and failed to find a working one:
I cannot use ajax since ajax is restricted only to the domain of the
page (advertisements are shown on external pages and cannot connect
to our server). An alternative approach is the use of a tracking pixel, but:
A tracking pixel needs some time to be loaded. If users click an <a>
tag then the pixel tracker added by myFunction() won't be loaded
before switching to the new page. I could prevent propagation of the
event, but:
The advertisement needs to get this click too. I tried to stop propagation of the event in javascript, load the pixel tracker, and then trigger the event again. Doesn't work - <a> tags are not clicked in this way - a click event triggered by javascript exists only on the javascript level.
Any suggestions would be appreciated.
Maybe you could something like this fiddle
<body>
<div id="linkContainer">
<a target="_blank" href="http://www.icrc.org/eng/">Link</a>
</div>
<script type="application/javascript">
$(document).ready(function(){
function beforeLeave(){
alert("Outa here!"); //Replace with function to do ajax-call to server
}
$('#linkContainer > a').on('click', function() {
beforeLeave();
});
});
</script>
</body>

How to enable and disable back button using JavaScript

I am using VS 2010.
I use two links to go back/forward between pages.
Code:
<img src="Images/back.jpg" />
<img src="Images/forward1.jpg"/>
It works well. Now I want to enable and disable the links based on browser history.
How do I do this using JavaScript?
As anchors are used for clicking, any other dom element also can be clicked. So,It is visually better to implement this functionality without using hyperlinks. Use code similar as below:
<p id="back"><img src="back.jpg"></p>
<p id="forward"><img src="forward.jpg"></p>
and event as below:
$("#back").click(function(){
if(!$(this).hasClass('disabled')) history.go(-1);
$(this).addClass('disabled');
$("#forward").removeClass('disabled');
});
$("#forward").click(function(){
if(!$(this).hasClass('disabled')) history.go(1);
$(this).addClass('disabled');
$("#back").removeClass('disabled');
});
User required style for .disabled.

JavaScript - href vs onclick for callback function on Hyperlink

I want to run a simple JavaScript function on a click without any redirection.
Is there any difference or benefit between putting the JavaScript call in the href attribute (like this):
....
vs. putting it in the onclick attribute (binding it to the onclick event)?
bad:
<a id="myLink" href="javascript:MyFunction();">link text</a>
good:
<a id="myLink" href="#" onclick="MyFunction();">link text</a>
better:
<a id="myLink" href="#" onclick="MyFunction();return false;">link text</a>
even better 1:
<a id="myLink" title="Click to do something"
href="#" onclick="MyFunction();return false;">link text</a>
even better 2:
<a id="myLink" title="Click to do something"
href="PleaseEnableJavascript.html" onclick="MyFunction();return false;">link text</a>
Why better? because return false will prevent browser from following the link
best:
Use jQuery or other similar framework to attach onclick handler by element's ID.
$('#myLink').click(function(){ MyFunction(); return false; });
Putting the onclick within the href would offend those who believe strongly in separation of content from behavior/action. The argument is that your html content should remain focused solely on content, not on presentation or behavior.
The typical path these days is to use a javascript library (eg. jquery) and create an event handler using that library. It would look something like:
$('a').click( function(e) {e.preventDefault(); /*your_code_here;*/ return false; } );
In terms of javascript, one difference is that the this keyword in the onclick handler will refer to the DOM element whose onclick attribute it is (in this case the <a> element), whereas this in the href attribute will refer to the window object.
In terms of presentation, if an href attribute is absent from a link (i.e. <a onclick="[...]">) then, by default, browsers will display the text cursor (and not the often-desired pointer cursor) since it is treating the <a> as an anchor, and not a link.
In terms of behavior, when specifying an action by navigation via href, the browser will typically support opening that href in a separate window using either a shortcut or context menu. This is not possible when specifying an action only via onclick.
However, if you're asking what is the best way to get dynamic action from the click of a DOM object, then attaching an event using javascript separate from the content of the document is the best way to go. You could do this in a number of ways. A common way is to use a javascript library like jQuery to bind an event:
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<a id="link" href="http://example.com/action">link text</a>
<script type="text/javascript">
$('a#link').click(function(){ /* ... action ... */ })
</script>
EDITOR WARNING: See the comments, the use of 'nohref' is incorrect in this answer.
I use
Click <a nohref style="cursor:pointer;color:blue;text-decoration:underline"
onClick="alert('Hello World')">HERE</a>
A long way around but it gets the job done. use an A style to simplify
then it becomes:
<style> A {cursor:pointer;color:blue;text-decoration:underline; } </style>
<a nohref onClick="alert('Hello World')">HERE</a>
The top answer is a very bad practice, one should never ever link to an empty hash as it can create problems down the road.
Best is to bind an event handler to the element as numerous other people have stated, however, do stuff works perfectly in every modern browser, and I use it extensively when rendering templates to avoid having to rebind for each instance. In some cases, this approach offers better performance. YMMV
Another interesting tid-bit....
onclick & href have different behaviors when calling javascript directly.
onclick will pass this context correctly, whereas href won't, or in other words no context won't work, whereas <a onclick="javascript:doStuff(this)">no context</a> will.
Yes, I omitted the href. While that doesn't follow the spec, it will work in all browsers, although, ideally it should include a href="javascript:void(0);" for good measure
the best way to do this is with:
The problem is that this WILL add a hash (#) to the end of the page's URL in the browser, thus requiring the user to click the back button twice to go to the page before yours. Considering this, you need to add some code to stop event propagation. Most javascript toolkits will already have a function for this. For example, the dojo toolkit uses
dojo.stopEvent(event);
to do so.
In addition to all here, the href is shown on browser's status bar, and onclick not. I think it's not user friendly to show javascript code there.
This works
Click Here
Having javascript: in any attribute that isn't specifically for scripting is an outdated method of HTML. While technically it works, you're still assigning javascript properties to a non-script attribute, which isn't good practice. It can even fail on old browsers, or even some modern ones (a googled forum post seemd to indicate that Opera does not like 'javascript:' urls).
A better practice would be the second way, to put your javascript into the onclick attribute, which is ignored if no scripting functionality is available. Place a valid URL in the href field (commonly '#') for fallback for those who do not have javascript.
it worked for me using this line of code:
<a id="LinkTest" title="Any Title" href="#" onclick="Function(); return false; ">text</a>
First, having the url in href is best because it allows users to copy links, open in another tab, etc.
In some cases (e.g. sites with frequent HTML changes) it is not practical to bind links every time there is an update.
Typical Bind Method
Normal link:
<a href="https://www.google.com/">Google<a/>
And something like this for JS:
$("a").click(function (e) {
e.preventDefault();
var href = $(this).attr("href");
window.open(href);
return false;
});
The benefits of this method are clean separation of markup and behavior and doesn't have to repeat the function calls in every link.
No Bind Method
If you don't want to bind every time, however, you can use onclick and pass in the element and event, e.g.:
Google
And this for JS:
function Handler(self, e) {
e.preventDefault();
var href = $(self).attr("href");
window.open(href);
return false;
}
The benefit to this method is that you can load in new links (e.g. via AJAX) whenever you want without having to worry about binding every time.
Personally, I find putting javascript calls in the HREF tag annoying. I usually don't really pay attention to whether or not something is a javascript link or not, and often times want to open things in a new window. When I try doing this with one of these types of links, I get a blank page with nothing on it and javascript in my location bar. However, this is sidestepped a bit by using an onlick.
The most upvoted answer is obsolete today
I would recommend the exact opposite, see step by step with reasons:
good:
<a id="myLink" href="javascript:MyFunction();">link text</a>
It depends, might be good, because crawlers follows href targets and if there is any meaningful content produced by MyFunction() (dynamic link), it is followed more likely than in the click event, which may have multiple or none listeners.
bad:
<a id="myLink" href="#" onclick="MyFunction();">link text</a>
# means meaningless link, crawlers are often interested only in first x links, so it can prevent them to follow some meaningful links later in the page.
worse:
<a id="myLink" href="#" onclick="MyFunction();return false;">link text</a>
Same as previous plus return false prevents following the link. If some other scripts want to add another listener and update the target (say to redirect via proxy), they can't without modifying the onclick (okay, it's just a minor setback as such use cases are rather theoretical).
worst:
Use jQuery or other similar framework to attach onclick handler by element's ID.
$('#myLink').click(function(){ MyFunction(); return false; });
jQuery is outdated in 2020+ and should not be used in new projects.
Events in href
The href attribute handler doesn't get the event object, so the handler doesn't implicitly see which link was the source. You can add it in onclick handler, which fires before the href is followed:
<a href="javascript:my_function(event2)" onclick="event2=event">
JS based link
</a>
<script>
function my_function(e) {
console.log(e.target); // the source of the click
if(something) location.href = ...; // dynamic link
}
</script>
One more thing that I noticed when using "href" with javascript:
The script in "href" attribute won't be executed if the time difference between 2 clicks was quite short.
For example, try to run following example and double click (fast!) on each link.
The first link will be executed only once.
The second link will be executed twice.
<script>
function myFunc() {
var s = 0;
for (var i=0; i<100000; i++) {
s+=i;
}
console.log(s);
}
</script>
href
onclick
Reproduced in Chrome (double click) and IE11 (with triple click).
In Chrome if you click fast enough you can make 10 clicks and have only 1 function execution.
Firefox works ok.
<hr>
<h3 class="form-signin-heading"><i class="icon-edit"></i> Register</h3>
<button data-placement="top" id="signin_student" onclick="window.location='signup_student.php'" id="btn_student" name="login" class="btn btn-info" type="submit">Student</button>
<div class="pull-right">
<button data-placement="top" id="signin_teacher" onclick="window.location='guru/signup_teacher.php'" name="login" class="btn btn-info" type="submit">Teacher</button>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('#signin_student').tooltip('show'); $('#signin_student').tooltip('hide');
});
</script>
<script type="text/javascript">
$(document).ready(function(){
$('#signin_teacher').tooltip('show'); $('#signin_teacher').tooltip('hide');
});
</script>
I experienced that the javascript: hrefs did not work when the page was embedded in Outlook's webpage feature where a mail folder is set to instead show an url
click here
I cant belive that +13 years later, all of these answers are semantically incorrect! An anchor element <a>:
...with its href attribute, creates a hyperlink to web pages, files, email addresses, locations in the same page, or anything else a URL can address.
Content within each should indicate the link's destination. If the href attribute is present, pressing the enter key while focused on the element will activate it.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a
Therefore, using an href= for javascript is bad practice and poor web semantics. You should rather be using an onclick= event handler attribute on a button element, as:
The HTML element is an interactive element activated by a user with a mouse, keyboard, finger, voice command, or other assistive technology. Once activated, it then performs a programmable action, such as submitting a form or opening a dialog.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button
and the event handler onclick=:
All event handler attributes accept a string. The string will be used to synthesize a JavaScript function like function name(/args/) {body}, where name is the attribute's name, and body is the attribute's value.
https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes#event_handler_attributes
As you are not navigating to a URL or a Link destination, but rather triggering a Javascript function the correct way to do this is to use onclick. And if you need the style of an anchor tag on a button, just use CSS.
The bottom line is: just because you can do it doesn't mean you should.
This works as well
<a (click)='myFunc()'>Click Here </a>
(onclick) did not work for me in an Angular project with bootstrap.

Categories

Resources