mazing
mazing

Reputation: 743

Rails javascript only works on double click, how to fix?

I have a simple "show/hide" button that hides or shows content. In my rails app though, however, it only functions after clicking twice. I would like to make it so only one click is needed.

application.js

//= require jquery_ujs
//= require tinymce-jquery
//= require_tree .

function showhide(){
  var div = document.getElementById("correct_answer_choice");
  if (div.style.display !== "none") {
    div.style.display = "none";
  }
  else {
    div.style.display = "block";
  }
}

Upvotes: 0

Views: 84

Answers (1)

Alex Santos
Alex Santos

Reputation: 2950

I can see you have jQuery installed. If you're not against using jQuery, an easier way is to use the toggle method:

function showhide(){
  $("#correct_answer_choice").toggle();
}

The toggle method tries to ensure that if it's visible prior to the function being called, then it will hide it, if it's hidden then it will show.

If that does not solve your issue, then I might need more information (for instance, how are you listening to the click and what's the initial state of the HTML)

Upvotes: 2

Related Questions