Ayush Goyal
Ayush Goyal

Reputation: 73

Changing the text of button without changing CSS styles

I am tinkering around with HTML and Javascript and have encountered a problem.

I have a button which animates on hover and changes text and color on click. When clicked again it goes back to the same color and text as before. This I am handling with a JS file.

My problem is that on clicking and hovering for the first time everything works fine but after first click, the animations are gone forever and the button now only changes color and text, no hover animation is there.

HTML for the button:

    <button class="button" style="vertical-align:middle" id="buttonclick" onclick="setColor()">
<span>Enable Control</span></button>

See this JSfiddle for full explanation.

Upvotes: 0

Views: 726

Answers (2)

Pradeep Rajput
Pradeep Rajput

Reputation: 725

You are changing innerHtml of the button. That replaces your span element with text.

Check your updated jsFiddle.

Upvotes: 1

Eztronics
Eztronics

Reputation: 518

Your explanation it's a bit vague and the title is a bit confusing. I suppose you want the same hover you had at the beggining (when you press the button and goes back to blue then the hover has to appear again). I will fix it:

The problem is that you are avoiding the span tag on your code line:

property.innerHTML = "Enable control"

You should change it to:

property.innerHTML = "<span>Enable control</span>"

The same goes in the else part:

 property.innerHTML = "<span>Disable control</span>"

Replace your Javascript code with this one fixed:

var count = 1;

function setColor() {
  var property = document.getElementById('buttonclick');
  if (count == 0) {
    property.style.backgroundColor = "#4f8ff7"
    property.innerHTML = "<span>Enable control</span>"
    alert("Disabled");
    count = 1;
  } else {
    property.style.backgroundColor = "#a84237"
    property.innerHTML = "<span>Disable control</span>"
    alert("Enabled");
    count = 0;
  }
}

Upvotes: 2

Related Questions