-1


So what I have is a bunch of:

<div class="panel-heading" id="@l.restaurant.id">

As you can see the ID of every DIV is a variable that the function will use. For exemple if I do this :

<div class="panel-heading" id="@l.restaurant.id" onclick="fun(this)"  >

The function works when I click the DIV, but I want that function to start as soon the page loads without me doing a thing.

mplungjan
  • 169,008
  • 28
  • 173
  • 236
Hodyr
  • 53
  • 7

3 Answers3

2

If you need to fun all panel-heading on load, then try

$(function() {
  $(".panel-heading").each(function() {
    fun(this);
  });
});

If you need to only run fun on divs that contain restaurant in the id, change the selector - $('.panel-heading[id*="restaurant"]')

mplungjan
  • 169,008
  • 28
  • 173
  • 236
0

You can get the element by id, and run you func on the element itself.

 fun(document.getElementById('@l.restaurant.id'))

If you use jQuery you can do it on page load

 $(function(){
     fun(document.\getElementById('@l.restaurant.id'))
 })

This is a short way to bind to document onload.

 $(document).on('ready',function(){
        // Your code
 ])

Example

Here is an example of a button that clicked on page load. When the user click the button, the background color of the button need to page change to blue. See that this is happen automatically.

function fun(element) {
  element.style.backgroundColor = 'blue'
}

$(function() {
  fun(document.getElementById('btn1'))
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Click a button, to change it's color:
<button id=btn1 onclick=fun(this)>btn1</button>
<button id=btn2 onclick=fun(this)>btn2</button>

More info...

It is not best practice, to bind event in the HTML code. it's always better to do this:

 $('#button_id').on('click',func)

When you do this, your func, will always have the element that you clicked as the context (this).

Then you can do:

 function(func){
           // this== document.getElementById('button_id')
 }

Why is using onClick() in HTML a bad practice?

Community
  • 1
  • 1
Aminadav Glickshtein
  • 23,232
  • 12
  • 77
  • 117
-1

Use a load event listener :)

window.addEventListener('load', function() {
  //the page has loaded; call your function
});
www139
  • 4,960
  • 3
  • 31
  • 56