flyingarmadillo
flyingarmadillo

Reputation: 2139

Rails: JQuery executing in console, not in js file

I am developing an app where users can post. I want to make it so that when a post's id is hashed in the url, the post flashes. To accomplish this, here is my code:

function getHash() {
  var hash = window.location.hash;
  return hash; 
}

if (getHash()) { 
    $(getHash()).fadeOut(300).fadeIn(300).fadeOut(300).fadeIn(300).fadeOut(300).fadeIn(300);
}

Now, I know this code is run b/c if I put an alert('in the if statement');, it works whenever there is a hash in the url. I also know this part works:

    $(getHash()).fadeOut(300).fadeIn(300).fadeOut(300).fadeIn(300).fadeOut(300).fadeIn(300);

because if I run it in the console, the post flashes. What is going wrong that is not allowing this to work?

Upvotes: 0

Views: 62

Answers (1)

Paritosh Singh
Paritosh Singh

Reputation: 6394

try your code like this

function getHash() {
  var hash = window.location.hash;
  return hash; 
}

$(document).ready(function(){
  if (getHash()) { 
    $(getHash()).fadeOut(300).fadeIn(300).fadeOut(300).fadeIn(300).fadeOut(300).fadeIn(300);
  }
})

I think since your element does not exist when your script is executing. Document ready works when whole document is prepared, and all your elements are in the place. Since everything seems fine, I think this will work

Thanks

Upvotes: 1

Related Questions