Jessica Jessica - 5 months ago 17
Javascript Question

jquery .click() is not registering an event listener when I start my webpage

I have a simple HTML page and an accompanyish javascript file. I want to trigger some javascript code when the user clicks on an image in a table. I added a jquery .click() function and I call that also from document.ready, but when I load the page I cannot click on the image. If I open F12 and manually write the jquery .click(), it becomes enabled, the eventlistener is registered, and I can click on the image to trigger the code. But not when just loading the page from IntelliJ.

Here is the HTML code:

<html lang="en">
<head>
<h1>My page</h1>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" type="text/css" href="mainpage.css">
<script type="text/javascript" src="http_code.jquery.com_jquery-2.0.0.js"> </script>
<script type="text/javascript" src="profile.js" ></script>
</head>
<body>
<p>This is my main page</p>
<table>
<tr>
<td>
<div id="image1">
<img src="images/fluffcat.jpg" align="left"/>
</div>
</td>
<td><img src="images/midsommarcat.jpg" align="center" id="image2"/></td>
<td><img src="images/tortillacat.jpg" align="right" id="image3"/></td>
</tr>
<tr>
<td>Cat 1</td>
<td>Cat 2</td>
<td>Cat 3</td>
</tr>
</table>
</body>
</html>


and here is the javascript file:

/**
* Created by jlg on 2016-06-11.
*/
function sayHello() {
console.log("Hello World")
}

function doClick() {
alert("something happened!");
window.open("Profile", "Profile", "", false);
}

function openPopup() {
console.log("I got here at least");
$("#image1").click(doClick);
}

function documentReadyFunctions() {
sayHello();
openPopup();
}

$( document ).ready(documentReadyFunctions());


What am I missing here? Is there some sort of ordering in the javascript file I'm missing? The "console.log("I got here at least");" shows up in the Console, as well as Hello World.

Answer

In the following code,

$(document).ready(documentReadyFunctions());

documentReadyFunctions() will call the function immediately and assign the returned value as callback to the ready.

And as the script is loaded in the <head>, by the time when this function is executed, the elements are not available in the DOM.

Remove the () invocation of the function.

$(document).ready(documentReadyFunctions);
//                ^^^^^^^^^^^^^^^^^^^^^^   // Don't call it, pass the function reference.

This will pass the function as reference and the function will be called when the DOM is ready.

Comments