I have an external *.js
file which contains the following code:
$(".hlavni_tema").click(function() {
alert("ok");
});
alert("loaded");
and an HTML page, as follows:
<div id="tema">
<span id="hlavni_tema_1" class="hlavni_tema">Základní fyzikální pojmy a jednotky</span>
<input type="checkbox" name="tema" id="tema_1a" value="'1a'">
<label for="tema_1a">Základní fyzikální pojmy, měření ve fyzice</label>
...
<span id="hlavni_tema_8" class="hlavni_tema">Astrofyzika</span>
<input type="checkbox" name="tema" id="tema_8d" value="'8d'">
<label for="tema_8d" class="posledni_label">Fyzikální obraz světa</label>
</div>
In the HEAD section, I include both the jQuery and external file sources, as follows:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="/_jscripts/tema.js"></script>
When I open the webpage, alert()
notifies "loaded"
, so that jQuery file is imported. But when I click on the span element whose class is "hlavni_tema"`, nothing happens. I've tried also with this code:
.on("click", function())
and
.on("click", "#tema", function())
-- all to no avail.
Thanks for any help.
Probably Dom is not ready when setting the event. Put your handler in a document ready
You have to assign event handlers after the DOM is loaded.
Try this, it should work.
Put the code inside
$(document).ready()
Otherwise, your code runs before the elements are added to the DOM, so the selector doesn't match anything.
I have checked the same code in Firefox, Google Chrome and Internet Explorer. And it is working in all the three browsers, may be you are adding click events before the Jquery files
Please check whether you have placed the click code in document.ready() function.
One of the most important things to know about jQuery is that one needs to be cognizant about when the DOM is fully loaded so that one's jQuery script may execute. A good recommendation is to code as follows:
$(document).ready(function() { // your code });
Or, you may use a shortened form with the anonymous function, as follows:
See here for more info.
Note ".ready()" pertains to when the DOM is fully loaded while the anonymous function is the handler for that event; see here.
Also, using the correct jQuery source-code URL matters, if you're not loading the library locally. To run the code at StackOverflow, I had to use
even tho' I could find the same url online prepended with "http" instead.
Note:
See this discussion.
Since optionally you may wish to check if the window has been fully loaded, too, this script includes that code as well.
Note: this code takes the liberty of adding some CSS code for demo purposes. Also, a good way to test is to replace the alert() statements with console.log() -- it's neater and saves one from having to dismiss anything.