Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running javascript for dropdown on page load?

I have a js function which controls the appearance of a select element upon change. However, the one thing i need is for the code to run from start so that when the element loads the selected options class should have already been applied.

css:

  select {height: 50px; width: 80px; border: solid 1px #c8c8c8; color:rgba(0, 0, 0, 0);}
select:focus, #select:focus {
  color:black;
}

.lightgrey {background: lightgrey}
.green {background:green}
.orange {background:orange}
.yellow {background:yellow}
.red {background:red}
.purple {background:purple}

JavaScript:

function colourFunction(select) {
        var colour = select.options[select.selectedIndex].className;

        select.className = colour;
        select.blur();
    }

Select:

<select class="selectElement" runat="server" id="dropdown_" onchange="colourFunction(this)">
                    <option selected="selected" class="lightgrey" value="N">N</option>
                    <option class="green" value="G">G</option>
                    <option class="orange" value="O">O</option>
                    <option class="yellow" value="A">A</option>
                    <option class="red" value="R">R</option>
                    <option class="purple" value="U">U</option>
                </select>

I want the class for N to be applied on load with color:rgba(0, 0, 0, 0);

like image 287
Singh Avatar asked May 14 '13 13:05

Singh


People also ask

Does JavaScript run on page load?

onload runs after page load and all javascript is available, so the codeAddress() function can be declared anywhere within the page or linked js files. It doesn't have to come before unless it were called during the page load itself.

How do you create a dropdown list in JavaScript?

Example Explained Use any element to open the dropdown menu, e.g. a <button>, <a> or <p> element. Use a container element (like <div>) to create the dropdown menu and add the dropdown links inside it. Wrap a <div> element around the button and the <div> to position the dropdown menu correctly with CSS.


2 Answers

if you're using jquery:

$(function(){
 //all onload actions you want
});

if you want to stick with pure js

document.onreadystatechange=function(){
//all onload actions you want
}
like image 165
Muhammad Bekette Avatar answered Oct 02 '22 15:10

Muhammad Bekette


If you're wanting the JS to run on page load, then you can use the "window.onload" command.

window.onload = function()
{
    colourFunction(select);
};
like image 38
Midnightly Coder Avatar answered Oct 02 '22 15:10

Midnightly Coder