nandu.com
nandu.com

Reputation: 343

How Can I add javascript for separate div's?

How can I give javascript for every div instead of the whole page?

<head>
    my jquery
    my javascript for the whole page
</head>
<body>
    <div id="cc1">
    Some content - I want to add Javascript for this div
    </div>
</body>

I know we add javascript only in head of the page or we call functions write in external js in onclick of html button events.

I need separate JS for each div because I am going to have a <noscript> in every div to show some static ad content if user has disabled javascript ; else if user has already enabled javascript, I am going to generate a dynamic ad content with my own javascript.

So how you do it?

Upvotes: 0

Views: 2172

Answers (3)

Jacob
Jacob

Reputation: 78848

It sounds like you're wanting to do something like this:

<div>
  <script type="text/javascript">
      document.write("Content A");
  </script>
  <noscript>
      Alternate content
  </noscript>
</div>

<div>
  <script type="text/javascript">
      document.write("Content B");
  </script>
  <noscript>
      Alternate content
  </noscript>
</div>

This is an old-fashioned way of doing things and I don't recommend it. An alternative to using inline script/noscript tags is to put the "noscript" content in the divs, then replace the content with JavaScript after the page loads; that way, if JavaScript is disabled, the original content will remain.

Upvotes: 2

CoursesWeb
CoursesWeb

Reputation: 4237

Hy

You can get a reference of that DIV, with var dvo = document.getElementById('id_div');

Then you can do and apply what you want to only that div.

Upvotes: 0

Masiar
Masiar

Reputation: 21352

If I get your question correctly, you cannot really add JavaScript for a div, you should add it for the whole page and then use it just in that div.

To make something happen inside that div, you have to work with <script> </script> tags and address that particular div. Otherwise just add another .js file on the head of the HTML file to make it do something on that div.

Upvotes: 0

Related Questions