0

I have html file with a few js files and jquery.

Scripts from file 1.js work fine. Scripts from file 2.js also work fine but Jquery don't works always. So I run some script and on result it should hide ".popup". Everything works – I run a message to console but events like hide() or click() don't work.

console.log("All done!");//works
console.log($(".popup"));//works fine – shows the right element in console

$(".popup").click();//doesn't work
$(".popup").hide();//doesn't work

I don't want to connect all scripts into one file and try to understand why there is always fine with scripts from one file and nothing works with another.

Any ideas?

Kir Mazur
  • 997
  • 2
  • 13
  • 27
  • you need to specify click handler or if you want to do click on that element then you need to use trigger.. that is $(".popup").trigger("click"); – Well Wisher Apr 09 '16 at 18:26

1 Answers1

1

Since we can't see much of your code, my answer is only a good guess:

The reason is that your javascript is executed before the DOM is rendered, therefore $(...) which tries to select your element, just can't find it at this moment.

That's why jQuery has a ready function, which will be executed once your DOM is ready: https://api.jquery.com/ready/

$(document).ready(function() {
      $(".popup").click();
      $(".popup").hide();
}

It works for your console.log statement because the value you pass to it is evaluated after the function is executed. (Actually i don't know the real reason for this, have to research myself)

Edit: Is Chrome's JavaScript console lazy about evaluating arrays? explains the reason for the console.log() behaviour (chrome only)

Community
  • 1
  • 1
malifa
  • 8,025
  • 2
  • 42
  • 57
  • Hi! Thanks for help. But I have $(document).ready(function() { – and nothing works. It's not so simple :( – Kir Mazur Apr 10 '16 at 08:22
  • Could you provide some more code. Your basic markup (how do you include your scripts..) and the scripts itself would help us to find your problem – malifa Apr 11 '16 at 11:34