1

I've tried to find answers on internet to this.. but I didn't find :(
I'm trying to call automatically a javascript function passing parameters inside a < div > element when the page is loaded.
I know that "onload" doesn't work on < div > elements. I don't have idea how to do that.

Note..: My parameters are dynamics because it's inside a foreach loop. Each loop I have 2 different parameters to send to the function.

@foreach(var i in Something)  
{  
  <div onload="myFunction(i.param1, i.param2);">  
  </div>
}
4
  • Add your Javascript function also Commented Jul 23, 2015 at 13:20
  • why don't you use <body onload="">? Commented Jul 23, 2015 at 13:22
  • Can you clarify why you want to do this? Specifying that will probably get you an answer explaining how to achieve this in a different and better way. Commented Jul 23, 2015 at 13:23
  • Ok. take a look now. Is it better? hehe Commented Jul 23, 2015 at 13:35

3 Answers 3

2

You can simply use a script block at the end of your <div>:

<div>
    ...
    <script type="text/javascript">
        myFunction(dynam_param1, dynam_param2);
    </script>
</div>
Sign up to request clarification or add additional context in comments.

2 Comments

Well, it worked good. I created a new <script> tag on the top of the page to make my function be global, so i can call it like you said. I dont know if its a great code.. but worked good.
Glad it worked for you. There are better ways using handlers for AJAX events, but this is way easier.
0

If you want to call the function when the page is loaded then you can put the onload in the <body> tag

<body onload="myFunction(dynam_param1, dynam_param2);">  

Comments

0

Update: I have updated my jsFiddle to show how to do using single script tag.

Assume below code is generated thru for loop.

<div class="dynamic-div" data-dynamic1='1' data-dynamic2='a'> 
    1
</div>
<div class="dynamic-div" data-dynamic1='2' data-dynamic2='b'> 
    2
</div>

So in your ready method you can get all the divs with class dyanmic-div and then do your process

$(document).on("ready", function(){
    $(".dynamic-div").each(function(index, element){
          var $this = $(element);
          myFunction($this.attr("data-dynamic1") , $this.attr("data-dynamic2"));            
    });
});

function myFunction(arg1, arg2){
    alert(arg1 + " - " +  arg2);            
}

http://jsfiddle.net/q8qzfavv

Here you can replace alert with your function call or any other operation that you plan to perform.

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.