Lessons 183 to 185 – Complete 2020 Web Development Bootcamp

Lesson 183 – Manipulating Text with JQuery

There are two ways of changing the text of a selected element using JQuery.

The first is –

$("h1").text("Bye");

The second is –

$("h1").html("<em>Bye</em>");

Lesson 184 – Manipulating Attributes using JQuery

You can manipulate attributes using JQuery attribute method like this –

$("a").attr("href", "https://www.yahoo.com");

This code will select all of the anchor tags on the website and change the href attribute to “https://www.yahoo.com”.

Lesson 185 – Adding Event Listeners with JQuery

You can add an event listener to an element using the JQuery .click() method. So for example, to an event listener to the h1 element, you would use the following code –

$("h1").click(function () {
  $("h1").css("color", "purple");
});

This code adds an event listener to the h1 element. On the h1 element being clicked, the anonymous function runs and changes the color of the h1 element to purple.

You can add a keypress event listener in JQuery with the following code –

$("input").keypress(function (event) {
  console.log(event.key);
});

This code adds a keypress event listener to the input area on the website and upon a keypress, the anonymous function runs and console logs which key was pressed.

The challenge in this lesson is to write JQuery code to detect a keypress and to change the h1 element’s text to whatever key was pressed.

$(document).keypress(function (event) {
  $("h1").text("event.key");
});

Instead of using the .click() or .keypress() method to add an event listener, you can use the .on() method. The .on() method takes two parameters.

The first parameter is the event you are listening for such as “mouseover”.

$("h1").on("mouseover", function() {
  $("h1").css("color", "purple");
});

In the above example, the second parameter is the anonymous function which will change the h1 element’s color to purple once a mouseover has been detected on the h1.