Once a web page is loaded in plain HTML, it is set. There's no more the browser can do with it to alter the image of a button, the style of a form, or the display of certain pieces of content. What the user sees is what the user gets.
divs for tabbed content.
How to Change up the HTML
So how do you change the HTML of a page after it's loaded to do all the neat things we've mentioned above? First, we must access the element:
document.getElementById("elementid").HTMLATTRIBUTE = "value";
<img id="slideshowimage" src="flower.jpg" alt="An image of a flower." />
Above is some basic HTML showing an image, with an id of "sideshowimage". We can use the id to style it any way we want in our stylesheet, just as anyone would expect. We've also given our image an
alt tag with an adequate description.
document.getElementById("slideshowimage").src = "bear.jpg";
alt tag to make it more relevant:
document.getElementById("slideshowimage").alt = "An image of a bear by the water.";
<img id="slideshowimage" src="bear.jpg" alt="An image of a bear by the water." />
<img src="image.gif" alt="An Image" id="myImage" style="padding: 5px; background: #fff; border: 1px solid #ccc;" />
As anyone can guess, we just place style for the HTML attribute when accessing the image:
document.getElementById("elementid").style.STYLEATTRIBUTE = "value";
document.getElementById("elementid").style = "padding: 5px; background: #fff; border: 1px solid #ccc;";
document.getElementById("elementid").style.padding = "10px"; document.getElementById("elementid").style.backgroundColor = "#aaa"; document.getElementById("elementid").style.border = "1px solid #555";
backgroundColor. In CSS, we would use
Events: Making it All Actually Happen
<button onClick="changeImage()">Change Image</button>
The code above creates a basic HTML button, and uses the
changeImage() function is called.
<button onClick="this.style.border = '2px solid #555'">Change Border</button>
Other Important and Commonly-Used Events
onLoad — Used in the
tag of an HTML page. The event triggers when the page is loaded. Example:
sayHello() function right when the page is loaded. Will re-trigger on every Refresh.)
onBlur — Triggers when an element is clicked, and then clicked off. A common use of this is in forms for validation. If a user clicked on field, then clicks away,
onBlur triggers when something is clicked away from.
onFocus — The opposite of
onBlur. Triggers when an element that can be focused is clicked. For example, a form input field.
onMouseDown, onMouseUp, onMouseOut, onMouseOver — All used with the interaction of the mouse. This is usually how image rollovers are created. When the mouse moves over an image -
onMouseOver, the image changes, and then changes again when it moves away from the image -
onMouseUp are similar, but with actual clicks of the mouse.
Check out Events and Event Handlers for more information on events and a more descriptive list of available events to use.