Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

call a javascript function inside a div

I would like to create a webpage which contains several divs each containing the same draw function with different implementation (like a generic interface). After loading the page I want to iterate through all the divs and call each draw function one after the other.

My page so far looks like this:

<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
  <script language="javascript" type="text/javascript" src="jquery-1.8.2.js"></script>
</head>
<body>

  <script type='text/javascript'>
    $( document ).ready( function() {
      // Draw all slots
      $('div.slot').each(function(i, d) {
        console.log('slot found: ' + d.id);
        // d.draw() does not work
        draw();
      });
    });
  </script>

  <div class="slot" id="slot1">
    <script type='text/javascript'>
      function draw() {
        console.log('Here we draw a circle');
      };
    </script>
  </div>

  <div class="slot" id="slot2">
    <script type='text/javascript'>
      function draw() {
        console.log('Here we do something totally different and draw a rectangle');
      };
    </script>
  </div>

</body>
</html>

Unfortunately I don't know how to call the draw function of the selected div "d". Right now it only calls the last defined draw function.

Update:

Mind you that I can not combine the different draw methods into one which would get a parameter like shape handed in. The draw methods will be totally independent from each other.

like image 780
Fabian Avatar asked Oct 23 '12 21:10

Fabian


1 Answers

Why are you defining scripts in the divs?

Do your logic all in one script block:

<head>      
<script language="javascript" type="text/javascript" src="jquery-1.8.2.js"></script>
</head>
<body>

  <script type='text/javascript'>
    $( document ).ready( function() {
      // Draw all slots
      $('div.slot').each(function(i, d) {
        console.log('slot found: ' + d.id);
        // d.draw() does not work
        draw();
      });
    });

    function draw(behavior) {
        console.log(behavior);
    }
  </script>

  <div class="slot" id="slot1" data-behavior="drew 1">
  </div>

  <div class="slot" id="slot2" data-behavior="drew 2">
  </div>

</body>
</html>

If you're looking to do something more complicated, you should consider building an object oriented javascript application, with each block's functionality derived from a class "slot".

https://developer.mozilla.org/en-US/docs/JavaScript/Introduction_to_Object-Oriented_JavaScript

like image 127
AndyL Avatar answered Sep 30 '22 01:09

AndyL