I'm trying to change the background color of the <div>
using javascript without clicking the <div>
itself. Basically the background color will change by itself or on load.
Here is my HTML
Code:
<div id="divChange" onclick="myDIV()">
<span class="glyphicon glyphicon-book" aria-hidden="true"></span> Passport <?php echo "<strong><a href=\"view_latest_passport.php?id=$id\"> $passport</a> / Passport Expiration Date:</strong> $passport_expiration"; ?>
</div>
and here's my javascript
code:
<script type="text/javascript">
function myDIV() {
document.getElementById("divChange").style.color="red";
}
</script>
Try it :
<html> <head></head> <body> <div id="divChange" onclick="myDIV()"> <span class="glyphicon glyphicon-book" aria-hidden="true"></span> Passport <?php echo "<strong><a href=\\"view_latest_passport.php?id=$id\\"> $passport</a> / Passport Expiration Date:</strong> $passport_expiration"; ?> </div> <script> document.getElementById("divChange").style.backgroundColor="red"; </script> </body> </html>
Use window.onload
event to trigger myDIV
method
//call your myDIV on window.onload window.onload = function(){ myDIV(); } function myDIV() { //this triggers only the text color document.getElementById("divChange").style.color="white"; //use this to change background color document.getElementById("divChange").style.backgroundColor="red"; }
<div id="divChange">Sample DIV</div>
Execute a JavaScript immediately after a page has been loaded, check link.
http://codepen.io/anil329/pen/kXvaPr
<html>
<head>
<title></title>
</head>
<body onload="myDiv()">
<div id="divChange">
<span class="glyphicon glyphicon-book" aria-hidden="true"></span> Passport
</div>
<script>
function myDiv() {
document.getElementById("divChange").style.color="red";
}
</script>
</body>
</html>
If you are using JQuery you can use this example .
$('document').ready(function() { var div = document.getElementById('divChange'); div.style.backgroundColor = 'red'; });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="divChange"> <span class="glyphicon glyphicon-book" aria-hidden="true"></span> Passport <strong><a href="view_latest_passport.php?id=$id"> My Passport</a> / Passport Expiration Date:</strong> 23 JUN 2015 </div>
Also you can use this code
<body onload="myDiv()"> ... <div id="divChange"> <span class="glyphicon glyphicon-book" aria-hidden="true"></span> Passport <strong> <a href="view_latest_passport.php?id=$id"> My Passport</a> Passport Expiration Date:</strong> 23 JUN 2015 </div> ... <script> function myDiv() { var div = document.getElementById( 'divChange' ); div.style.backgroundColor = 'red'; } </script> </body>
Call your myDIV() method onload event.
<body onload="myDIV()">
your content goes here.
</body>
Thanks.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.