Jump to content

Recommended Posts

I have to use this html and create a javascript file to make the buttons GROW, BLUE, FADE and RESET function.  I am doing prework for a coding class and am a beginner.  

<!DOCTYPE html>
<html>
<head>
    <title>Watch That Box</title>
</head>
<body>

    <p>Press the buttons to change the box!</p>

    <div id="box" style="height:150px; width:150px; background-color:orange; margin:25px"></div>

    <button id="button1">Grow</button>
    <button id="button2">Blue</button>
    <button id="button3">Fade</button>
    <button id="button4">Reset</button>

    <script type="text/javascript" src="javascript.js"></script>

</body>
</html>
Link to post
Share on other sites

@Jason908 LOL, I haven't done any DOM Javascript for a long time ... here's one approach for javascript.js:

// get a reference to the box and cache the initial style for resetting
const box = document.getElementById( 'box' );
const initStyle = box.style.cssText;

// what to do when clicked, using the text within the button as identifier
function onClick( event )
{
	switch( event.target.innerHTML )
	{
		case 'Grow':
			box.style.width = box.style.height = '300px';
			break;
		case 'Blue':
			box.style.backgroundColor = 'blue';
			break;
		case 'Fade':
			box.style.opacity = 0.5;
			break;
		case 'Reset':
			box.style.cssText = initStyle;
			break;
	}
}

// add the click event listener to all the buttons
[...document.getElementsByTagName( 'button' )].forEach( function( button )
{
	button.addEventListener( 'click', onClick );
} );

Please do better!  My vanilla JS isn't so great after years of Haxe.

I intentionally introduced a switch and a loop because they are fun to know.  I also think that calling the DOM is dumb - so many risks with it not being as expected.

Have fun!

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
  • Recently Browsing   0 members

    No registered users viewing this page.

×
×
  • Create New...