0

I am trying to write a javascript function so that when a button is clicked, all HTML paragraph elements "p" will be highlighted yellow, the HTML buttons text will then change to "Click to unhighlight" (the code below before the else statement is fully functional, all paragraphs are highlighted and the buttons text changes). I am trying to reload the page using "location.reload();" but it doesn't seem to work.

window.onload = function() {
  var button = document.getElementsByTagName("button");
  button[0].onclick = changeBackground;
}

function changeBackground() {
  var myParas = document.getElementsByTagName("p");

  for (var i = 0; i < myParas.length; i++) {
    myParas[i].style.backgroundColor = "yellow";
  }
  var firstClick = true;
  var b = document.getElementById("button");

  if (firstClick) {
    b.innerHTML = "Click to unhighlight";
    firstClick = false;
  } else {
    location.reload();
    firstClick = true;
  }
}

Any advice on how to properly call the "location.reload();" function would be much appreciated. Thanks in advance.

3
  • 2
    How would firstClick ever be false? Commented Oct 29, 2018 at 21:43
  • and location.reload(); firstClick = true; would make no sense - once you've triggered the reload, any code you write after that is pointless because you've just told the browser to destroy the page and re-create it from scratch. But you don't need a reload for this, anyway Commented Oct 29, 2018 at 21:46
  • Why do you want to reload the page if it's not the first click? Commented Oct 29, 2018 at 21:54

3 Answers 3

3

Your main issue is that you have:

var firstClick = true;

inside the click event handler so every time the button is clicked, it thinks it's the first click. You'd need to have that set outside of the event handler and inside, you'd want to toggle it to the opposite of its current value:

var firstClick = true;

function changeBackground() {
  var myParas = document.getElementsByTagName("p");

  for (var i = 0; i < myParas.length; i++) {
    myParas[i].style.backgroundColor = "yellow";
  }

  var b = document.getElementById("button");

  if (firstClick) {
    b.textContent = "Click to unhighlight";
  } else {
    location.reload();
  }

  firstClick = !firstClick; // Toggle the first click variable
}

But, really instead of reloading the document, just un-highlight the paragraphs. Reloading takes more resources.

Avoid using getElementsByTagName() as it returns a "live node list", which has performance implications.

Also, rather than set up an explicit onload event handler, just position your code at the bottom of the HTML body.

Lastly, use modern standards for event handling (.addEventListener), rather than event properties (onclick).

See comments inline below:

// Place all this code inside of a `<script>` element and place that
// element at the bottom of the code, just before the closing body tag.

let btn = document.querySelector("button"); 

// Modern, standards-based way to set up event handlers
btn.addEventListener("click", changeBackground);

function changeBackground() {
  // Use .querySelectorAll() and convert the results to an array
  var myParas = Array.prototype.slice.call(document.querySelectorAll("p"));

  // Loop over all the paragraphs
  myParas.forEach(function(par){
    // Toggle the CSS class to highlight/or unhighlight them
    par.classList.toggle("highlight");
  });
  
  // Set the button text accordingly
  btn.textContent = myParas[0].classList.contains("highlight") ? "Click to unhighlight" : "Click to highlight";  
}
.highlight { background-color:yellow; }
<p>This is a test</p>
<h1>This is a test</h1>
<p>This is a test</p>
<p>This is a test</p>
<div>This is a test</div>
<p>This is a test</p>
<p>This is a test</p>
<button>Click to highlight</button>

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much for those inline comments, I have a lot of JS learning to do.
and thanks a lot for taking my initial version and providing a functional solution.. thanks for doing what you do.
0

the problem is that the else sentence never be call, because the "firstClick" variable always will be true each time you call the changeBackGround method you're setting the variable to true.

to avoid this, just declare the variable out of the method, example:

var firstClick=true;
function changeBackground(){
    var myParas = document.getElementsByTagName("p");

    for (var i = 0; i < myParas.length; i++) {
        myParas[i].style.backgroundColor = "yellow";
    }

    var b = document.getElementById("button");

    if (firstClick){
        b.innerHTML = "Click to unhighlight";
        firstClick = false;
    }else{
        location.reload();
        firstClick = true;
    }
}

Comments

0

A different approach is to use switch case.

<button id="changeButton">Make my paragraphs Yellow</button>
<script>
var theToggle = document.getElementById("changeButton");
var toggleMe = document.getElementsByTagName("p");
toggleMe.toggleStatus = "on";

theToggle.onclick = function(){
  switch(toggleMe.toggleStatus){
    case "on":
      toggleMe.toggleStatus="off";
      for (var i = 0; i < toggleMe.length; i++) { toggleMe[i].style.backgroundColor = 'yellow'; }     
      theToggle.textContent = "Make my paragraphs White";
      break;
    case "off":
      toggleMe.toggleStatus="on";
      for (var i = 0; i < toggleMe.length; i++) { toggleMe[i].style.backgroundColor = 'white'; }      
      theToggle.textContent = "Make my paragraphs Yellow";
      break;
  }
 }
</script>

Hope that solve it.

3 Comments

Why use a two case switch, instead of a simple boolean?
And why two loops instead of one?
I respect your comments and others answers but In my opinion this much easy way to toggle. Another benefit is if you want to add more cases (ie black background and white text) for accessibility purpose etc...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.