Jason908 Posted January 8, 2021 Share Posted January 8, 2021 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> Quote Link to comment Share on other sites More sharing options...
b10b Posted January 13, 2021 Share Posted January 13, 2021 @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! Quote Link to comment Share on other sites More sharing options...
Recommended Posts
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.