I am beginner to coding and js. I have been looking to get started on a little project to change text (i.e. the word "cat") to another piece of text (i.e. dog) on hover? Please help, anything simple to get me started.
-
You should edit the question to include what you have tried so far. Otherwise, it's impossible to know where you are having trouble. Also, take a look at [how to ask](https://stackoverflow.com/help/how-to-ask) for tips on creating effective questions. – Mark Nov 27 '18 at 00:30
2 Answers
I guess what you are trying to achieve raises the following two basic questions:
- How do you change the text of an element?
- How do you trigger this change when hovering over the element?
To answer your first question you may check out this webpage to find out about basic dom manipulation. You can also have a look at the following code snippet to see how to permanently change a text with "cat" to "dog".
var text = document.getElementById('text')
text.textContent = "dog"
<p id="text">
cat
</p>
To answer your second question you should read about eventlistener. In this case particular you probably want to use the events mouseover and mouseout. The following snippet will provide an example of how to use them:
var text = document.getElementById('text')
text.addEventListener("mouseout", function() {
text.textContent = "cat"
})
text.addEventListener("mouseover", function() {
text.textContent = "dog"
})
<p id="text">
cat
</p>
Since you seem to be a new learner I could also recommend you to read about window.onload since you may be running into some trouble when executing the lines like var text = document.getElementById('text')
too early.
Also, you could have a look at the difference between innerHTML and textContent as mentioned by Nick Parsons in a comment. It's actually cleaner to use textContent in this case since we only want to change a text.

- 175
- 1
- 12
-
Nice explanation. Since the OP seems to be a learner maybe it would be of use to use `.textContent` rather than `.innerHTML`. `.innerHTML` can have security issues with XSS (if used in other ways), and letting them know about `.textContent` may be beneficial for them down the line. – Nick Parsons Nov 27 '18 at 02:04
This code changes the link text to whatever you have in "data-change", and changes it back again on mouse out.
<a href="#" data-change="Dog" onmouseover="changeMe(this)" onmouseout="changeMe(this)">Cat</a>
<script type="text/javascript">
function changeMe(el) {
newText = el.getAttribute('data-change');
oldText = el.innerText;
el.setAttribute('data-change', oldText);
el.innerText = newText;
}
</script>

- 1,169
- 6
- 17