0

I have an issue regarding the jQuery click event. The first time the page get loaded it does not work. After a refresh it works fine. I assume it has to do with the browser caching the files somehow.

This is the code:

$(window).ready(
    function() {

        $("#language-input").click(function() {
            $("#language-dropdown").show();
        });

Any ideas what I am missing?

atlas
  • 361
  • 4
  • 13
  • 2
    out of curiosity, why are you using `$(window).ready` instead of `$(document).ready`? – Difster Jul 31 '17 at 07:35
  • No particular reason.$(document).ready might be a better idea. – atlas Jul 31 '17 at 07:44
  • `$(window).ready` will be executed after all the external resources are fully loaded, images, iframe content etc. Some of these might be cached, and the loading happens faster when refreshing. `$(document).ready` executes immediately after all the HTML has been parsed, it doesn't wait images or iframes to be fully loaded. – Teemu Jul 31 '17 at 07:44

2 Answers2

1

Instead of

$("#language-input").click(function() {

You can use

$("#language-input").on('click', function() {.

This will ensure that the click event is fired even if the element is loaded dynamically.

You final code would be without $(window).ready(function() { :

$("#language-input").on('click', function() {
    $("#language-dropdown").show();
});
Milan Chheda
  • 7,851
  • 3
  • 18
  • 35
  • 1
    That's not how event delegation works. `$("x").click(` is **just shorthand for** `$("x").on("click", ` https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements – freedomn-m Jul 31 '17 at 07:58
  • Well, if the element is loaded dynamically than `click` won't work. You need to use `on` for it. And this would ensure that an event is clicked every-time whenever user clicks it. – Milan Chheda Jul 31 '17 at 08:02
  • 2
    I agree that if the element is loaded dynamically then `click` won't work, but *neither will* `$("element").on("click"` as they are the same. You're looking for `$(document).on("click", "#element", function() ...` – freedomn-m Jul 31 '17 at 08:04
  • I believe both should work, though not sure. Let me add your suggestion too in the answer and wait for the OP to check or share more details. What say? – Milan Chheda Jul 31 '17 at 08:05
0

The solution, which was mentioned in one of the comments, was to use:

$(document).on("click", "#element", function()

This seemed to work for dynamically added elements.

atlas
  • 361
  • 4
  • 13