JavaScript for optimizers: Exercise answers

Exercise 1:

var picture = document.querySelector(".hidethisimage");
picture.style.display = "none";

Exercise 2:

//replace title
var getTitleNode = document.querySelector("h1");
var newTitle = "Changing titles is easy";
var getHeaderElement = document.querySelector(".entry-header-inner");
getTitleNode.innerText = newTitle;
//add subtitle
var newSubtitle = document.createElement("h2");
var newSubtitleNode = document.createTextNode(
  "It will be even better with a subtitle."
);
newSubtitle.appendChild(newSubtitleNode);
getHeaderElement.appendChild(newSubtitle);
// add another subtitile
var anotherSubtitle = document.createElement("h3");
var anotherSubtitleNode = document.createTextNode(
  "I can add new titles!"
);
anotherSubtitle.appendChild(anotherSubtitleNode);
getHeaderElement.appendChild(anotherSubtitle);

Exercise 3:

var block1 = document.querySelector(".block1");
var block3 = document.querySelector(".block3");
function moveUp(element) {
  if (element.previousElementSibling)
    element.parentNode.insertBefore(element, element.previousElementSibling);
}
function moveDown(element) {
  if (element.nextElementSibling)
    element.parentNode.insertBefore(element.nextElementSibling, element);
}

moveUp(block3);

Exercise 4:

var singleLink = document.querySelector(".testLink1 > a");
var multipleLinks = document.querySelectorAll(".testLinks > a");

function replaceSingleLinkWithButton(link) {
  var newButton = document.createElement("button");
  var newButtonText = document.createTextNode(link.innerText);
  newButton.appendChild(newButtonText);
  var newButtonLink = link.getAttribute("href");
  var parentNode = link.parentNode;
  var newAnchor = document.createElement("a");
  newAnchor.setAttribute("href", newButtonLink);
  newAnchor.appendChild(newButton);
  parentNode.appendChild(newAnchor);
  link.remove();
}

function replaceMultipleLinksWithButtons(links) {
  for (var i = 0; i < links.length; i++) {
    var newButton = document.createElement("button");
    var newButtonText = document.createTextNode(links[i].innerText + " " + i);
    newButton.appendChild(newButtonText);
    var newButtonLink = links[i].getAttribute("href");
    var parentNode = links[i].parentNode;
    newButton.setAttribute("style", "margin-right:5px;margin-bottom:5px;");
    var newAnchor = document.createElement("a");
    newAnchor.setAttribute("href", newButtonLink);
    newAnchor.appendChild(newButton);
    parentNode.appendChild(newAnchor);
    links[i].remove();
  }
}

replaceSingleLinkWithButton(singleLink);
replaceMultipleLinksWithButtons(multipleLinks);

Exercise 5:

var maleRadio = document.getElementById("male");
var otherRadio = document.getElementById("other");
var rangeSlider = document.getElementsByClassName("slider");

function changeRadioSelection(oldButton, newButton) {
  oldButton.removeAttribute("checked");
  newButton.setAttribute("checked", "checked");
}
changeRadioSelection(maleRadio, otherRadio);

function changeRangeValue(range, value) {
  range[0].setAttribute("value", value);
}
changeRangeValue(rangeSlider, "0");

Exercise 6:

var prices = document.querySelectorAll(".price");
function removeCurrency(node) {
  for (var i = 0; i < node.length; i++) {
    var price = node[i].innerHTML;
    var price = price.replace(/₹ /g, "€ ");
    var price = price.replace(/€ /g, "€ ");
    var price = price.replace(/\$ /g, "€ ");
    node[i].innerHTML = price;
  }
}
removeCurrency(prices);

Exercise 7:

var warning = document.querySelector(".warning");
var productBlock = document.querySelector(".countdown");
productBlock.innerHTML = "--" + " MIN " + "--" + " SEC ";
var todayDate = new Date();
var targetDate = todayDate.setDate(todayDate.getDate() + 1);
//var targetDate = new Date("Jan 1, 2023 16:32:55").getTime();

var x = setInterval(function() {
  var nowDate = new Date();
  var difference = targetDate - nowDate;
  var minutes = Math.floor((difference % (1000 * 60 * 60)) / (1000 * 60));
  var seconds = Math.floor((difference % (1000 * 60)) / 1000);
  productBlock.innerHTML = minutes + " MIN " + seconds + " SEC ";
  if (difference < 0) {
    clearInterval(x);
    productBlock.style.display = "none";
    warning.style.display = "none";
  }
}, 1000);

productBlock.style.color = "#d72756";
productBlock.style.textAlign = "center";
productBlock.style.border = "1px solid #d72756";
productBlock.style.borderRadius = "4px";
warning.innerHTML = "THE DISCOUNT IS ALMOST OVER:";
warning.style.textAlign = "center";
warning.style.color = "#d72756";
warning.style.fontSize = "24px";
warning.style.fontWeight = "bold";

Exercise 8:

//declaring variables
var getAddToCartButtons = document.querySelectorAll(
  ".add-to-cart > div > div > div > a > i"
);

//changing the icon of multiple buttons
for (var i = 0; i < getAddToCartButtons.length; i++) {
  if (i % 2 == 0) {
  //the condition checks if the current loop is an even number
    let getAddToCartButtonsClassList = getAddToCartButtons[i].classList;
    getAddToCartButtonsClassList.replace("fa-plus-square", "fa-cart-plus");
  }
}

Exercise 9:

var getSubscribeButton = document.querySelector(".subscribe > div > a");
var getRegisterButton = document.querySelector(".register > div > a > i");
var newIconSubscribeButton = document.createElement("i");
newIconSubscribeButton.setAttribute("style", "padding-left:5px;");
newIconSubscribeButton.setAttribute("class", "fas fa-envelope-open-text");
getSubscribeButton.append(newIconSubscribeButton);
getRegisterButton.style.display = "none";

Exercise 10:

var dateInput = document.querySelector("#date");
var supported = true;
var test = document.createElement("input");

try {
  test.type = "date";
} catch (e) {
  supported = false;
}

if (supported) {
  dateInput.setAttribute("type", "date");
  dateInput.setAttribute("value", getFormattedDate(0));
  dateInput.setAttribute("min", getFormattedDate(-2));
  dateInput.setAttribute("max", getFormattedDate(2));
}

function getFormattedDate(changeYear) {
  var today = new Date();
  var dd = String(today.getDate()).padStart(2, "0");
  var mm = String(today.getMonth() + 1).padStart(2, "0");
  var yyyy = today.getFullYear() + changeYear;
  formattedDate = yyyy + "-" + mm + "-" + dd;
  return formattedDate;
}

Exercise 11:

//variables
var getToggleVideoButton = document.querySelector(".toggle > a");
var getVideoDiv = document.querySelector(".is-provider-youtube");

//eventlisteners
getToggleVideoButton.addEventListener("click", toggleVideo);

//functions
function toggleVideo() {
  if (getVideoDiv.style.display === "none") {
    getVideoDiv.style.display = "block";
    getToggleVideoButton.innerText = "Hide video";
  } else {
    getVideoDiv.style.display = "none";
    getToggleVideoButton.innerText = "Show video";
  }
}

//change default text button
getToggleVideoButton.innerText = "Hide video";

Exercise 12:

//variables
var getCopyToClipboardButton = document.querySelector(".clipboard > a");
var getCouponCode = document.querySelector(".couponCode").innerText;

//event listeners
getCopyToClipboardButton.addEventListener("click", function() {
  copyToClipboard(this, getCouponCode);
});

//functions
function copyToClipboard(button, code) {
  var tempInput = document.createElement("input");
  tempInput.style = "position: absolute; left: -1000px; top: -1000px";
  tempInput.value = code;
  document.body.appendChild(tempInput);
  tempInput.select();
  document.execCommand("copy");
  document.body.removeChild(tempInput);
  disableButton(button);
  copyAgain();
}

function disableButton() {
  getCopyToClipboardButton.style.transition = "1s";
  getCopyToClipboardButton.innerHTML = `COPIED TO CLIPBOARD <i class="fas fa-clipboard-check"></i>`;
  getCopyToClipboardButton.style.backgroundColor = "#549612";
}

function copyAgain() {
  getCopyToClipboardButton.addEventListener("mouseover", function() {
    getCopyToClipboardButton.style.backgroundColor = "#d72756";
    getCopyToClipboardButton.innerHTML = `Copy to clipboard <i class="fas fa-clipboard"></i>`;
  });
}

Exercise 13:

//variables
let refreshLocation = document.querySelector(".entry-content");

//functions
function createRefreshButton(location) {
  let containerDiv = document.createElement("div");
  let refreshButton = document.createElement("button");
  let refreshButtonText = document.createTextNode("Soft refresh page");
  refreshButton.appendChild(refreshButtonText);
  refreshButton.classList.add("refreshButton");
  containerDiv.appendChild(refreshButton);
  location.prepend(containerDiv);
  document
    .querySelector(".refreshButton")
    .addEventListener("click", refreshPage);
}

function refreshPage() {
  location.reload(false);
}

//function call
createRefreshButton(refreshLocation);

Exercise 14:

//variables
var usps = [
  "Easy to learn",
  "Can be used for many tools",
  "Fun to use",
  "Free"
];
var loc = document.querySelector(".entry-content");

//functions
function addUniqueSellingPoints(usps, loc) {
  var ul = document.createElement("UL");
  for (i = 0; i < usps.length; i++) {
    var le = document.createElement("LI");
    var usp = document.createTextNode(usps[i]);
    le.appendChild(usp);
    ul.appendChild(le);
  }
  loc.prepend(ul);
}

//function calls
addUniqueSellingPoints(usps, loc);