0

This question comes from

Actually, I was able to find a clue and this is what I found. I have a js file:

$(document).ready(function() {
  var myIdElement = $("#some_id");

  //............
  $.ajax({
    url: getFullUrl(myIdElement.val())
  })
  //..........

So when I come to this page from the another page by a link (html link) then myIdElement is undefined. However, when I reload the page it starts having a proper value. I use turbolinks.

How do I get it to work in all situations?

Incerteza
  • 32,326
  • 47
  • 154
  • 261
  • var myIdElement = $("#some_id").val(); try this – Amit Jun 28 '14 at 08:14
  • well you shouldnt be getting undefined for your variable... even when jQuery cannot find an element you at least get a jQuery object back. – Patrick Evans Jun 28 '14 at 08:16
  • And `#some_id` is initially in the DOM when the page is first rendered? Or do you add it via JS later? Also are you sure the [DOM is valid?](http://validator.w3.org/) Also do you know how to use the javascript debugger in your browser? Try to set a breakpoint on that line and look how the DOM looks at that moment. – s1lv3r Jun 28 '14 at 08:16
  • @Amit, this was a typo in my code. – Incerteza Jun 28 '14 at 08:30
  • @s1lv3r, yes, it is there initially. – Incerteza Jun 28 '14 at 08:31
  • 1
    use var myIdElement = $("#some_id").val(); instead of var myIdElement = $("#some_id"); –  Jun 28 '14 at 08:39

2 Answers2

1

$(document).ready does not always fire in turbolink. Use page:load event, instead. On the first page, it fires ready event, but on subsequent pages, document has always been ready, hence no document ready event is fired. So, it fires page:load to help us.

function ready () {
  // Your code goes here...
}

jQuery(document).ready(ready);
jQuery(document).on('page:load', ready);
Jashwant
  • 28,410
  • 16
  • 70
  • 105
0

Try this:

(function($) {
$(document).ready(function() {
  var myIdElement = $("#some_id");

  //............
  $.ajax({
    url: getFullUrl(myIdElement.val())
  })
  //..........
})(jQuery);
Tuong Le
  • 18,533
  • 11
  • 50
  • 44
  • doesn't `(function($) {` itself mean the same as `$(document).ready(`? – Incerteza Jun 28 '14 at 08:40
  • @AlexanderSupertramp, no it means, a variable is passed as `$` in anonymous function. You are getting it confused with jQuery's `document.ready` shorthand notation which is, `$(function() {});`. See http://stackoverflow.com/questions/6004129/document-ready-shorthand – Jashwant Jun 28 '14 at 09:40
  • why should `(function($) {` help? – Incerteza Jun 28 '14 at 12:49
  • It will help in cases where other libraries are used and `$` is overwritten. Using this technique, we are safe to use `$`for `jQuery`, even if `$` has been assigned another value. – Jashwant Jun 28 '14 at 14:11