0

Problem statement :In my code I have onclick and href on one element and I want to call href first. I searched every where but I found opposite solution i.e first click event trigger then href calls.

See this example: http://jsfiddle.net/kevalbhatt18/y5qmLmxk/2/

var tmp1 ="www.mysite.com"

document.body.innerHTML+='<div style="margin-left:10;"><li class="highlight"><a href="'+tmp1+'"  onclick="highlightSearch(this);">test Span</a></li></div>';

function highlightSearch(scope){
    event.preventDefault();
    var href = scope.href
    window.location = href;

    console.log('ddd');

}

I tried without preventDefault same thing happens, so i thought i can call href in click event like above example. but it gives me same result.

So it is possible to call href first, then other part of click.

Edit :

see in console when you run fiddle.

you can see console print first then href called. so my quetion is different

Keval Bhatt
  • 6,224
  • 2
  • 24
  • 40
  • 1
    Why do you want to trigger link before `onclick`? It will open a new page and script will not be executed (or will be executed but result will be anyway lost). – Yeldar Kurmangaliyev Jul 08 '15 at 06:18
  • Your href can't be a javascript `alert`, I can't understand what you are trying to do – michelem Jul 08 '15 at 06:19
  • I'm sorry but I did not understand your question. Can you tell me what you expect to happen when you click on the `test Span` link? – Ahs N Jul 08 '15 at 06:21
  • The href javascript will get called by the browser.. WHen ever you try to access the href of that anchor. Even if you try to access from you code.AS you did with "scope.href" [check](https://jsfiddle.net/abhisek101088/y5qmLmxk/1/) – Abhisek Malakar Jul 08 '15 at 06:32
  • 1
    `var tmp1 ="alert('href')"` change it to `var tmp1 ="javascript:alert('href')"` if what you want is to show an alert. – rrk Jul 08 '15 at 06:53

0 Answers0