| ||||||
|
How to change the CSS cursor property dynamically with JavaScript getElementById()
Previously I have discussed how various cursor styles can be accessed via CSS. This current tutorial will go one step further, and give an insight how the cursor property can be changed to another setting dynamically once the page has already been loaded. To access the cursor property we will be using the JavaScript function getElementById(). If you are not as of yet familiar with this function I suggest you read an introduction tutorial first. Here then is how the cursor property can be changed via getElementById(): document.getElementById(elementId).style.cursor = 'pointer'; Of course pointer could be replaced with a number of cursor styles. Here is the above code embedded inside a function which allows the user to choose from numerous cursor styles: <html> <head> <title>Changing the css cursor property</title> <script language="javascript" type="text/javascript"> function changeCursor(newCursor, elementId) { document.getElementById(elementId).style.cursor = newCursor; } </script> <style type="text/css"> <!-- body { text-align:center; } div { cursor:default; background:#CCCCFF; text-align:center; border:1px #111 solid; margin-top: 30px; width:400px; height:200px; margin:auto; padding-top:90px; } --> </style> </head> <body> <div id="id1">Hover your mouse here to see the current cursor setting!</div> <br> <input style="padding-right:5px;" type="button" onclick="changeCursor('default', 'id1');" value="Default"> <input style="padding-right:5px;" type="button" onclick="changeCursor('pointer', 'id1');" value="Pointer"> <input style="padding-right:5px;" type="button" onclick="changeCursor('crosshair', 'id1');" value="Crosshair"> <input style="padding-right:5px;" type="button" onclick="changeCursor('progress', 'id1');" value="Progress"> <input style="padding-right:5px;" type="button" onclick="changeCursor('wait', 'id1');" value="Wait"> <input style="padding-right:5px;" type="button" onclick="changeCursor('help', 'id1');" value="Help"> <input style="padding-right:5px;" type="button" onclick="changeCursor('move', 'id1');" value="Move"> </body> </html>
|