# Dynamically add javascript tag to a view

**URL:** <https://www.ruby-forum.com/t/dynamically-add-javascript-tag-to-a-view/133167>\
**Category:** Rails\
**Created:** [March 28, 2008, 1:31pm UTC](https://www.ruby-forum.com/t/dynamically-add-javascript-tag-to-a-view/133167 "2008-03-28T13:31:11Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![joel](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/b9bd4f/32.png) [@joel](https://www.ruby-forum.com/u/joel)\
**Post date:** [March 28, 2008, 1:31pm UTC](https://www.ruby-forum.com/t/dynamically-add-javascript-tag-to-a-view/133167/1 "2008-03-28T13:31:11Z")

</div>

Hi everybody,

I would like to add javascript tags dynamically to my view. So I used  
the following code :

@events.each do |e|

```
      %(javascript_tag 'new

```

Popup(‘event\_popup\_#{e.id}’,‘event\_link\_#{e.id}’)’)

end

However it seems the code is not being added to my DOM.

How can I correctly code this ?

Thanks in advance.

Joel

---

<div class="post-metadata">

**Author:** ![joel](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/b9bd4f/32.png) [@joel](https://www.ruby-forum.com/u/joel)\
**Post date:** [March 28, 2008, 1:49pm UTC](https://www.ruby-forum.com/t/dynamically-add-javascript-tag-to-a-view/133167/2 "2008-03-28T13:49:38Z")

</div>

What’s wrong with doing this:

?

On Fri, Mar 28, 2008 at 11:00 PM, joel [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> 

–  
Ryan B.

> **[frozenplague.net](http://www.frozenplague.net)**
>
> This domain may be for sale!

Feel free to add me to MSN and/or GTalk as this email.

---

<div class="post-metadata">

**Author:** ![joel](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/b9bd4f/32.png) [@joel](https://www.ruby-forum.com/u/joel)\
**Post date:** [March 28, 2008, 2:05pm UTC](https://www.ruby-forum.com/t/dynamically-add-javascript-tag-to-a-view/133167/3 "2008-03-28T14:05:45Z")

</div>

Yes of course 😉 !

Thank you very much…

Joel

---

<div class="post-metadata">

**Author:** ![joel](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/b9bd4f/32.png) [@joel](https://www.ruby-forum.com/u/joel)\
**Post date:** [March 29, 2008, 12:42am UTC](https://www.ruby-forum.com/t/dynamically-add-javascript-tag-to-a-view/133167/4 "2008-03-29T00:42:48Z")

</div>

joel wrote:

> end  
> %() declares a string literal, so nothing happens to your  
> javascript\_tag. And  
> .each won’t return your string - even the correct one.

Try this eRB:

\<%=  
@events.map do |e|  
javascript\_tag “new  
Popup(‘event\_popup\_#{e.id}’,‘event\_link\_#{e.id}’);”  
end  
%\>

That still has its own style issues, including it will push several

tags in, not just one efficient one. You could also try this: \<%= javascript\_tag @events.map{|e| "new Popup('event\_popup\_#{e.id}','event\_link\_#{e.id}');" }.join %\> So that puts the tag on the outside, and the "unrolled loop" on the inside. -- Phlip
