A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://webplatform.github.io/docs/tutorials/manipulating_css_with_javascript below:

Manipulating CSS with JavaScript · WebPlatform Docs

Manipulating CSS with JavaScript Summary

In this article we look at the basics of how to manipulate CSS styles using JavaScript.

Information: JavaScript

JavaScript is a programming language. JavaScript is widely used to provide interactivity in web sites and applications. JavaScript can interact with stylesheets, allowing you to write programs that change a document’s style dynamically.

There are three ways to do this:

Action: A JavaScript demonstration
  1. Make a new HTML document, doc5.html. Copy and paste the content from here, making sure that you scroll to get all of it:

    <!DOCTYPE html>
    <html>
    
    <head>
    <title>Mozilla CSS Getting Started - JavaScript demonstration</title>
    <link rel="stylesheet" type="text/css" href="style5.css" />
    <script type="text/javascript" src="script5.js"></script>
    </head>
    
    <body>
    <h1>JavaScript sample</h1>
    
    <div id="square"></div>
    
    <button type="button" id="clickMe">Click Me</button>
    
    </body>
    </html>
    
  2. Make a new CSS file, style5.css. Copy and paste the content from here:

    #square {
      width: 20em;
      height: 20em;
      border: 2px inset gray;
      margin-bottom: 1em;
    }
    
    button {
      padding: .5em 2em;
    }
  3. Make a new text file, script5.js. Copy and paste the content from here:

    
    
    var square = document.getElementById("square"),
        clickMe = document.getElementById('clickMe'); 
    function doDemo () {
    
      var button = this;
      square.style.backgroundColor = "#fa4";
      button.setAttribute("disabled", "true");
      setTimeout(clearDemo, 2000, button);
    }
    
    function clearDemo (button) {
      var square = document.getElementById("square");
      square.style.backgroundColor = "transparent";
      button.removeAttribute("disabled");
    }
    
    clickMe.onclick = doDemo; 
    
  4. Open the document in your browser and press the button.

What this code does, is that it changes the background color of the #square to #ffaa44. Here’s a JSFiddle so you can see it working live.

Notes on what is happening in the above example:

See also Exercise question

Change the script so that the square jumps to the right by 20 em when its color changes, and jumps back afterwards.

Attributions

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4