doyz
doyz

Reputation: 886

Simple Jquery toggle not working

I have a really simple Jquery function that mimicks the code in many online tutorials, an i have looked at a couple of similar stackoverflow questions, but i can't understand why nothing happens when i click the link to show/hide the div called 'advanced-search'. (I have also removed turbolinks but nothing happens too. I do have other Jquery codes present throughout the app and all work fine).

articles/index.html.erb

    <div class="advanced-search">
       Some code
    </div>

    <a class="show-advanced-search">Advanced Search</a>

articles.js

$(document).ready(function(){
  $('.show-advanced-search').click(function(){
    $('.advanced-search').toggle();  
  });
});

Narrowing selector down to 'a.show-advanced-search' does not work either.

EDIT:

I have another Jquery file called "articles.coffee" below with an ajax callback, thought that it could be the one affecting the other jQuery code. However, i have tried deleting "articles.coffee" and the same issue remains.

Copying and pasting the code in articles.js into the browser console works. No errors in browser console.

articles.coffee

jQuery(document).on 'change', 'select.sortBy', () ->
  $.ajax(
    url: $(this).data('url') + '?type=' + this.value
    type: 'GET'
    contentType: 'script'
    processData: false
  )
  return

my original application.js file

//= require rails-ujs
//= require jquery
//= require bootstrap-sprockets
//= require jquery_ujs
//= require jquery.transit.js
//= require turbolinks
//= require articles.js
//= require_tree .

Upvotes: 1

Views: 125

Answers (4)

doyz
doyz

Reputation: 886

I fixed it by combining the articles.coffee and articles.js files.

articles.coffee

jQuery(document).on 'click', 'a.show-advanced-search', () ->
    $('.advanced-search').toggle()

Seems as though having 2 separate files and even specifying both in application.js do not work.

Upvotes: 0

jon snow
jon snow

Reputation: 3072

If you have included jquery.js and articles.js in order. Then next issue could be turbolinks If you are using it.

$( document ).on('turbolinks:load', function() {
  // Do your code
})

NOTE : on Rails >= 4 its there. Please check that.

Upvotes: 1

Saeed
Saeed

Reputation: 118

hi try this as articles.js

    $(document).ready(function(){
  $('.show-advanced-search').click(function(){
    $('.advanced-search').toggle();  
  });
});

jsfiddle

Upvotes: 0

Jar3d
Jar3d

Reputation: 116

If it's loaded at the same time the page loads, it shouldn't present any error. But if this is part of the code of a pop-up that appears after clicking on a button you should try this:

<pre>$(document).ready(function(){
  // we assum the pop-up container loads at the same time the page is loaded
  $('div.pop_up_container').on("click",".show-advanced-search",function(){
    $(this).next('.advanced-search').toggle();
  });
});</pre>

Upvotes: 0

Related Questions