1

I have a simple div in one of my views that I want to click to hide another element on the page. I put this in my application.js But it doesn't do anything. Did I put it in the wrong place?

function toggleNewPostForm {
    $('.new-post-btn').hide();
}
3
  • The question is: is the function (toggleNewPostForm) really triggered when clicking? Commented Apr 27, 2015 at 11:59
  • 1
    Uncaught SyntaxError: Unexpected token { is what you should see in your error console Commented Apr 27, 2015 at 11:59
  • I rely too much on webstorm and when i switched to sublime this happens. Thanks alot! Commented Apr 27, 2015 at 12:03

3 Answers 3

1

Use document ready to make sure document is loaded before selecting an element from HTML and call your function inside

function toggleNewPostForm(){
  $('.new-post-btn').hide();
};

$( document ).ready(function() {
  toggleNewPostForm();
});
Sign up to request clarification or add additional context in comments.

1 Comment

this will yield a syntax-error as function <name>{<body>}() is not a valid function-definition...
0

Try something like this

<div class="xyz">Click here!</div>

in javascript

$(".xyz").click(function(){
  $('.new-post-btn').hide();
});

Also check if event listener is added after document ready method? i.e

$(function(){
   $(".xyz").click(function(){
     $('.new-post-btn').hide();
   });
});

2 Comments

In ruby on rails, you should check against 'page:load' and 'ready' as a document-ready-Handler (because of Turbolinks...)
Sure, if someone is using turbolinks (which is by default in use since rails 4) then he should check for both page:load and ready events
0

If this is the only js you have, there will be no click-behaviour. You have to tell the element, that is has to react to a click-event.

Try this in your application.js-file:

function toggleNewPostForm() {
    $('.new-post-btn').hide();
}

$(document).on('ready page:load', function(){
    $('.new-post-btn').on('click', function(){
        toggleNewPostForm();
    });
});

P.S.: As RGraham points out, you have to write the parameter-paranthesis if you define a function.

P.P.S.: In ruby on rails, you should check against 'ready' and 'page:load' as document-ready-handlers, because Ruby on Rails uses the "Turbolinks"-library by default.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.