Home HTML JavaScript DOM Data Types

Following allong

  • Create a new markdown file in _posts (you will be able to put HTML in here)
  • You can try the concepts we are doing here on that post

Getting HTML elements in your javascript

  • To get an HTML element, use document.getElementById("the id here")
  • You will use the ID that you set in your HTML
  • if you console.log the resulting variable you will get some information about the element
%%html
<!-- the ID must be specified on the element -->
<h1 id="title1">My Title</h1>

<!-- our javascript goe here -->
<script>
var titleElement = document.getElementById("title1")
console.log("Example #1")
console.log(titleElement)
</script>

My Title

Basics of Objects

  • Our variable titleElement stores an “object”
  • Basically think of this as a group of data
    • Example “name” is a variable
    • BUT Student #10’s name is more specific, in this case Student #10 is the object
    • The name of Student #10 would be referred to as Student #10.name rather than name
  • To access a certain type of data from an “object” we use “.” notation
    • ie. To get the content of this titleElement, we would do titleElement.innerHTML
%%html
<!-- the ID must be specified on the element -->
<h1 id="title2">My Title</h1>

<!-- our javascript goe here -->
<script>
var titleElement = document.getElementById("title2")
console.log("Example #2")
console.log(titleElement.innerHTML)
</script>

My Title

Modifying the HTML

  • We can treat the data in this “object” (the html element) as a variable
    • Therefore, we can change the value using the “=” (assignment) operator
%%html
<!-- the ID must be specified on the element -->
<h1 id="title3">My Title</h1>

<!-- our javascript goe here -->
<script>
var titleElement = document.getElementById("title3")
titleElement.innerHTML = "A better title"
</script>

My Title

Functions with Objects

  • Functions allow you to “do something”
    • ex. “eat food”
  • We have used functions in a few of the examples
    • console.log = “print something”
    • document.getElementById = “find an element with id”
  • Functions take in parameters, what to do (inside the parenthesis)
    • ex. we have to tell console.log what to print
    • ex #2. we have to tell document.getElementById what the id of the elemt is
  • Functions can be used with objects as well
    • Example: doWork (who is doing the work)
    • With Objects: Student #10, doWork (Student #10.doWork())
    • The parenthesis after indicate it is a function (parameters can go in there as well)

Creating elements

  • We can create an element with the document.createElement function -> takes in the type of element
  • We can set properties in the element just like we did with the h1
%%html
<!-- the ID must be specified on the element -->
<div id="container1">
    <h1 id="title10">My Title</h1>
</div>

<!-- our javascript goe here -->
<script>
   // creates a new element
   var pElement = document.createElement("p")
   pElement.innerHTML = "some text"
</script>

My Title

Issue!

  • We don’t see the element
  • Here is a visualization of what is happening => the “p” is not placed inside the page! visual on p tag floating

Solution

  • We need to place the element somewhere
  • For example, we could add the element to the div
    • For this, we use the appendChild function on the div object (the parameter would be the p element we created)
    • Remember, we can use getELementById to get the object for something in the html (the div!)
  • Updated Diagram visual on p tag in div
%%html
<!-- the ID must be specified on the element -->
<div id="container2">
    <h1 id="title11">My Title</h1>
</div>

<!-- our javascript goe here -->
<script>
   // creates a new element
   var pElement = document.createElement("p")
   pElement.innerHTML = "some text"

   // place the p element in the webpage
   var div = document.getElementById("container2")
   div.appendChild(pElement)
</script>

My Title

Creeating functions

  • We were using functions for a lot of this functionality, but how can we create our own?
  • Useful to avoid writing the same code over and over again
  • We define parameters (they effectively become variables), and return “output” of the function
    • ie. getStudent(name); parameters = name; returns the actual student
  • See the example below
%%html
<!-- the ID must be specified on the element -->
<div id="container5">
    <h1 id="title15">My Title</h1>
</div>

<!-- our javascript goe here -->
<script>
    // create a function => takes in text, returns created p
    function createPTag(text) {
        // creates a new element
        var pElement = document.createElement("p")

        // using the parameter like a variable
        pElement.innerHTML = text

        return pElement;
    }

    // using our new function
    var pTag = createPTag("cooler text")

    // place the p element in the webpage
    var div = document.getElementById("container5")
    div.appendChild(pTag)
</script>

My Title

Reactivity

  • We can run functions when an event happens
    • In this case, we will add the p tag when the button is clicked
%%html
<!-- the ID must be specified on the elements -->
<button id="myButton">Click here!</button>

<div id="myContainer">
    <h1 id="myTitle">My Title</h1>
</div>

<!-- our javascript goe here -->
<script>
    // create a function => takes in text, returns created p
    function createPTag(text) {
        // creates a new element
        var pElement = document.createElement("p")

        // using the parameter like a variable
        pElement.innerHTML = text

        return pElement;
    }

    // create a function that sets specific text and adds to div
    function addCoolPTag() {
        // using our new function
        var pTag = createPTag("cooler text")

        // place the p element in the webpage
        var div = document.getElementById("myContainer")

        // add p tag to the div
        div.appendChild(pTag)
    }

    // add the P tag when our button is clicked
    var myButton = document.getElementById("myButton")

    // using the onclick variable of the button
    // functions can be used as values for these variables
    myButton.onclick = addCoolPTag
</script>

My Title

Hacks

%%html
   <style>
        button {
            background-color: #4E804F;
            color: white;
            padding: 10px 20px;
            border: none;
            cursor: pointer;
        }
        button:hover {
            background-color: darkgreen;
        }
        a {
            color: white;
            text-decoration: none;
        }
        a:hover {
            color: #D1D9CE;
        }
        /* Additional styles for better presentation */
        div {
            margin: 20px;
        }
        .top {
            background-color: #4E804F;
            padding: 10px 0;
            text-align: center;
        }
        .top a {
            margin: 0 20px;
        }
        h1 {
            text-align: center;
        }
    </style>
</head>
<body>
    <header>
        <h1> Online Grocery Store! </h1>
    </header>
    <nav class=top>
        <a href=/> Home</a>
        <a href=/fruits> Fruits</a>
        <a href=/vegetables> Vegetables</a>
        <a href=/dairy> Dairy</a>
    </nav>
    <section>
        <h2>Shop Now</h2>
        <p>Explore a wide variety of fresh and delicious groceries.</p>
        <button>Start Shopping</button>
    </section>
    <section>
        <h2>Our Products</h2>
        <p>Discover the finest selection of fruits, vegetables, and dairy products.</p>
        <a href=/fruits>Fruits</a>
        <a href=/vegetables>Vegetables</a>
        <a href=/dairy>Dairy</a>
    </section>
</body>
</html>
<script>
    // Function to switch the links and change the text
    function switchLinks() {
      // Get the two <a> elements
      const link1 = document.querySelector('.top a:nth-child(2)');
      const link2 = document.querySelector('.top a:nth-child(3)');
  
      // Switch the href attributes
      const tempHref = link1.getAttribute('href');
      link1.setAttribute('href', link2.getAttribute('href'));
      link2.setAttribute('href', tempHref);
  
      // Change the inner HTML of the top <p> tag
      const topParagraph = document.querySelector('.top p');
      topParagraph.innerHTML = 'Switched!';
    }
  
    // Add an event listener to the button
    const button = document.querySelector('button');
    button.addEventListener('click', switchLinks);
  </script>
  

</head>

☆ Online Grocery Store! ☆

<nav class=“top”> <a href=“/”>☆ Home</a> <a href=“/fruits”>☆ Fruits</a> <a href=“/vegetables”>☆ Vegetables</a> <a href=“/dairy”>☆ Dairy</a> </nav>

Shop Now

Explore a wide variety of fresh and delicious groceries.

Our Products

Discover the finest selection of fruits, vegetables, and dairy products.

<a href=“/fruits”>Fruits</a> <a href=“/vegetables”>Vegetables</a> <a href=“/dairy”>Dairy</a>

</html>