3

I've been trying to simulate click on a tag and this is not working as i need it to. my anchor tag looks like this

<a href="/dl/pic.jpg" target="_blank" download="file.jpg"> Download this pic </a>

a normral $("a").click() or trigger('click') wont work here.Any ideas? EDIT I need to trigger a click on this Anchor tag and causing the file to download, i dont need to add another onClick function.

1
  • $('a').on('click', function(e){e.preventDefault();alert("clicked");}); Commented Jun 23, 2013 at 13:23

4 Answers 4

9

Using native js click event works:

http://jsfiddle.net/n6FKg/

$('a').get(0).click();
Sign up to request clarification or add additional context in comments.

4 Comments

cant use indicator, this is dynamically created and doesnt have fixed position in order of Anchors
I'm just telling you that using jquery to trigger click on anchor doesn't work but using js native click() works. How you target this element is up to you. In you question, you said: $("a").click() wont work. Then i show you how to make it works... If you have more than one anchor to trigger click, then use a loop from get()
By position, you mean index??? The question is how do you want to target a specific anchor? Sorry but your question is really too vague and incomplete.
Yaah, it did worked, can you guide me about 'what does get(0) does'?
1

You can achieve this using JavaScript itself by adding an id attribute

<a id="download" href="/dl/pic.jpg" download="file.jpg"> Download this pic </a>

document.getElementById("download").click();

Comments

0

Few options here:

  1. The link is added dynamically, in that case binding click won't work, you need to do something like this:

     ('#linkContainer').on('click','a',function(){//do stuff});
    
  2. the click does work, but since its an a tag, it has a default behaviour and it goes to the href, so you need to add in the function e.preventDefault

4 Comments

you didnt understand the question, i dont need adding another funcationality , i just need to trigger this file download from other place.
You didn't understand my answer, as it does exactly what you need, with no extra functionality added
i need to default click to go to the href..i need to trigger the file to download.
That is not what your question says, please update your question and explain exactly what you need
0

add the path to the file to be downloaded to the hrefattribute not to download attribute

<a href="/dl/file.jpg" target="_blank"> Download this pic </a>

1 Comment

do u have the intended file kept at that path? coz this is the only way a file download should work?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.