Jessica Jessica - 1 year ago 74
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">
<h1>My page</h1>
<meta charset="UTF-8">
<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>
<p>This is my main page</p>
<div id="image1">
<img src="images/fluffcat.jpg" align="left"/>
<td><img src="images/midsommarcat.jpg" align="center" id="image2"/></td>
<td><img src="images/tortillacat.jpg" align="right" id="image3"/></td>
<td>Cat 1</td>
<td>Cat 2</td>
<td>Cat 3</td>

and here is the javascript file:

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

function doClick() {
alert("something happened!");"Profile", "Profile", "", false);

function openPopup() {
console.log("I got here at least");

function documentReadyFunctions() {

$( 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 Source

In the following code,


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.

//                ^^^^^^^^^^^^^^^^^^^^^^   // 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download