Javascript and partials

Hi,

I have a lot of javascript functions that can’t be executed when I
render a
partial.
I mean. There are functions that area described inside a js file and
when a
partial that calls some functions from that file is rendered, nothing
occurs.

How can I execute a javascript function when a partial is rendered ?

Thanks.

On Apr 22, 2015, at 7:40 AM, Gm [email protected] wrote:

Hi,

I have a lot of javascript functions that can’t be executed when I render a
partial.
I mean. There are functions that area described inside a js file and when a
partial that calls some functions from that file is rendered, nothing occurs.

How can I execute a javascript function when a partial is rendered ?

Can you say a little more about how you are rendering these partials?
Are you using remote: true to inject them into the page with JavaScript
views, or are you rendering the whole page? If the latter, are you using
Turbolinks? You may need to wrap your JavaScript in an event listener
for the page:change event.

Walter

Hi,

I have this simple function inside a js file:

$(‘input:button’).click(function() {
$(’#panel’).removeClass(‘hidden’);
});

When I render a partial with a button inside:

The click function inside js.file is not executed.
I think it’s because the js file is “included” in the main page, and
inside
the partial that js is not available.

Walter, thanks for your help.
I’ll try to modify my code to this approach.

Thank you.

Thank you sir.
Works like a charm.

When I render a partial with a button inside:

The click function inside js.file is not executed.
I think it’s because the js file is “included” in the main page, and inside the
partial that js is not available.

Almost. It’s because that js has already ‘seen’ the page, and your
button wasn’t in it when it ‘looked’, so it didn’t register the click
handler on it. Take a look at the deferred listener functions, using the
on() method in jQuery or Prototype. Those let you set up a listener at a
higher level (like the page, or just a parent to the element in your
partial), and then it doesn’t matter if the button was injected after
the fact or not.

In Prototype:

document.on('click', 'input[type="button"]', function(evt, elm){
  // do something
});

Walter