How to launch a function(this) from an html element automatically

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.

Answers


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"]')


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>

Use a load event listener :)

window.addEventListener('load', function() {
  //the page has loaded; call your function
});

Need Your Help

Combining CommandLine Option Parsers with Scopt

scala command-line scopt

I am currently using scopt for a Command Line Application. However My scopt.OptionParser[Config] is getting very large. I was thinking it might be nice to break it into smaller parts, and then comb...

How do I search in HTML generated by Restclient?

ruby-on-rails ruby

How can I search for a word in the HTML generated by the Restclient::Response module?