pedroyanky pedroyanky - 5 months ago 44
Javascript Question

click event not producing the expected result

I have this code that looks clean and fine, but it is not producing the desired result.


<div class="div1">
<p>This is the first paragraph inside the division</p>
<p>This is the second paragragh inside the division</p>
<h5>This is a h5 header</h5>
<p>This is a paragraph next to he h5 header</p>
<a href="#" class="ankor" >justklick</a>


jQuery(document).ready(function () {
function click(ev) {
var ev = window.event;
var anchor = document.querySelector('.ankor');
anchor.onClick = click();

I actually expected to see the name of the event in my console, instead this is what i am having as the result "DOMContentLoaded".

Can anybody tell me a reason for this?


By appending () you are executing click immediately inside your jQuery(document).ready(function () { Inside this block, you are assigning var ev = window.event which is what you see when you console/log: DomContentLoaded is the window event, as execution is inside the document/ready block.

One way to avoid your problem is to substitute the following:

anchor.onClick = click();

With the following which only executes on click, instead of immediately:

$(anchor).on('click', click);