To add sound effects in JavaScript and HTML5, we call the play method.
For instance, we write
const snd = new Audio("file.wav");
snd.play();
to create an Audio object that plays file.wav.
Then we call play to start playing the file.
Web developer specializing in React, Vue, and front end development.
To add sound effects in JavaScript and HTML5, we call the play method.
For instance, we write
const snd = new Audio("file.wav");
snd.play();
to create an Audio object that plays file.wav.
Then we call play to start playing the file.
To display a confirmation dialog when clicking an anchor link with JavaScript, we can call the confirm function in the click handler.
For instance, we write
const reallySure = (event) => {
const message = "Are you sure about that?";
const action = confirm(message);
if (!action) {
event.preventDefault();
}
};
const actionToFunction = (event) => {
switch (event.target.tagName.toLowerCase()) {
case "a":
reallySure(event);
break;
default:
break;
}
};
document.body.addEventListener("click", actionToFunction);
to call document.body.addEventListener with 'click' to add the actionToFunction click handler to the body element.
In actionToFunction, we check if an a element is clicked by getting the tag name of the element clicked with event.target.tagName.
If 'a' is returned after converting it to lower case, then we call reallySure.
In it, we call confirm to check if the user wants to confirm the action.
And if the user cancels, we call preventDefault to stop the default click behavior.
To disable all div content with CSS, we set the pointer-events property.
For instance, we write
#my-div {
pointer-events: none;
}
to select the div with ID my-div and disable all mouse events on it by setting pointer-events to none.
To find the closest ancestor element that has a specific class with JavaScript, we use the closest method.
For instance, we write
const closest = document.querySelector("p").closest(".near.ancestor");
to select the p element with querySelector.
And then we get the closest element from it with classes near and ancestor with the closest method.
To find the width of a div using vanilla JavaScript, we use the offsetWidth or clientWidth property.
For instance, we write
const offsetWidth = document.getElementById("myDiv").offsetWidth;
const clientWidth = document.getElementById("myDiv").clientWidth;
to select the div with getElementById.
And then we get the width of the div with the offsetWidth or clientWidth properties.
offsetWidth includes border width, and clientWidth does not.