I'm trying to implement some native Javascript code so that when you mouse over a heading the heading will change color.
I will put all the JS code at the bottom with he HTML so you can see it in context but the bit of code I've added to my .js file is as follows:
//change <h2> on mouseover/mouseout
document.getElementsByClassName("heading2").onmouseover.style.color="red";
The HTML document:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Session 5 - Dynamic Menu</title>
<link rel="stylesheet" type="text/css" href="styles.css">
<script src="dynamicmenu.js"></script>
</head>
<body>
<h1>Web Programming Languages</h1>
<h2>JavaScript</h2>
<p>
JavaScript (JS) is an interpreted puter programming language. As part of web browsers, implementations allow client-side scripts to interact with the user, control the browser, municate asynchronously, and alter the document content
</p>
<h2>PHP</h2>
<p>
PHP is a server-side scripting language designed for web development but also used as a general-purpose programming language. PHP is now installed on more than 244 million websites and 2.1 million web servers. Originally created by Rasmus Lerdorf in 1995, the
</p>
<h2>Ruby</h2>
<p>
Ruby is a dynamic, reflective, object-oriented, general-purpose programming language. It was designed and developed in the mid-1990s by Yukihiro "Matz" Matsumoto in Japan.Ruby embodies syntax inspired by Perl with Smalltalk-like features and was also influenced by Eiffel and Lisp. It supports multiple programming paradigms, includin
</p>
<h2>ASP</h2>
<p>
Active Server Pages (ASP), also known as Classic ASP or ASP Classic, was Microsoft's first server-side script engine for dynamically generated web pages. Initially released as an add-on to Internet Information Services (IIS) via the Windows NT 4.0 Option Pack (ca. 1996), it was subsequently included as a free
</p>
<h2>Java Server Pages</h2>
<p>
Architecturally, JSP may be viewed as a high-level abstraction of Java servlets. JSPs are translated into servlets at runtime; each JSP's servlet is cached and re-used until the original JSP is modified.
</p>
</body>
</html>
The Javascript Code:
//function to create dynamic menu...
function dynamicMenu() {
//Get all <h2> headings in to a container
var headings = document.getElementsByTagName("h2");
//Create <div> for menu
var menu = document.createElement("div");
//Set id attribute for <div>
menu.setAttribute("id", "navWrap")
//Create <ul> for menu list items
var menuUL = document.createElement("ul");
//Set id attribute for <ul>
menuUL.setAttribute("id", "mainNav");
//Append the <ul> to the <div> as a child
menu.appendChild(menuUL);
//Set up loop to populate menu
for (var i = 0; i < headings.length; i++) {
//Collect the text content of h2 headings
var linkText = headings[i].childNodes[0].nodeValue;
//Create <li> element
var menuULitem = document.createElement("li");
//Append <li> to <ul> as child
menuUL.appendChild(menuULitem);
//Create <a> tag element
menuAtag = document.createElement("a");
//Append <a> to <li> as child
menuULitem.appendChild(menuAtag);
//Set the <a> href attribute to point to the anchor tag in body of document
menuAtag.setAttribute("href", "#item" + i)
//Append link text as a hchild of <a>
var menuText = document.createTextNode(linkText);
menuAtag.appendChild(menuText);
//Create an anchor point for each <h2>
var anchor = document.createElement("a");
//Set anchor attribute name
anchor.setAttribute("name", "item" + i);
//Insert anchor in to DOM
document.body.insertBefore(anchor, headings[i]);
//Give headings a class attribute
headings[i].setAttribute("class", "heading2");
}
//Insert the Menu created in above loop in to the DOM
document.body.insertBefore(menu, document.body.firstChild);
//change <h2> on mouseover/mouseout
document.getElementsByClassName("heading2").onmouseover.style.color="red";
}//close function (dynamicMenu)
window.onload = dynamicMenu;
I'm trying to implement some native Javascript code so that when you mouse over a heading the heading will change color.
I will put all the JS code at the bottom with he HTML so you can see it in context but the bit of code I've added to my .js file is as follows:
//change <h2> on mouseover/mouseout
document.getElementsByClassName("heading2").onmouseover.style.color="red";
The HTML document:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Session 5 - Dynamic Menu</title>
<link rel="stylesheet" type="text/css" href="styles.css">
<script src="dynamicmenu.js"></script>
</head>
<body>
<h1>Web Programming Languages</h1>
<h2>JavaScript</h2>
<p>
JavaScript (JS) is an interpreted puter programming language. As part of web browsers, implementations allow client-side scripts to interact with the user, control the browser, municate asynchronously, and alter the document content
</p>
<h2>PHP</h2>
<p>
PHP is a server-side scripting language designed for web development but also used as a general-purpose programming language. PHP is now installed on more than 244 million websites and 2.1 million web servers. Originally created by Rasmus Lerdorf in 1995, the
</p>
<h2>Ruby</h2>
<p>
Ruby is a dynamic, reflective, object-oriented, general-purpose programming language. It was designed and developed in the mid-1990s by Yukihiro "Matz" Matsumoto in Japan.Ruby embodies syntax inspired by Perl with Smalltalk-like features and was also influenced by Eiffel and Lisp. It supports multiple programming paradigms, includin
</p>
<h2>ASP</h2>
<p>
Active Server Pages (ASP), also known as Classic ASP or ASP Classic, was Microsoft's first server-side script engine for dynamically generated web pages. Initially released as an add-on to Internet Information Services (IIS) via the Windows NT 4.0 Option Pack (ca. 1996), it was subsequently included as a free
</p>
<h2>Java Server Pages</h2>
<p>
Architecturally, JSP may be viewed as a high-level abstraction of Java servlets. JSPs are translated into servlets at runtime; each JSP's servlet is cached and re-used until the original JSP is modified.
</p>
</body>
</html>
The Javascript Code:
//function to create dynamic menu...
function dynamicMenu() {
//Get all <h2> headings in to a container
var headings = document.getElementsByTagName("h2");
//Create <div> for menu
var menu = document.createElement("div");
//Set id attribute for <div>
menu.setAttribute("id", "navWrap")
//Create <ul> for menu list items
var menuUL = document.createElement("ul");
//Set id attribute for <ul>
menuUL.setAttribute("id", "mainNav");
//Append the <ul> to the <div> as a child
menu.appendChild(menuUL);
//Set up loop to populate menu
for (var i = 0; i < headings.length; i++) {
//Collect the text content of h2 headings
var linkText = headings[i].childNodes[0].nodeValue;
//Create <li> element
var menuULitem = document.createElement("li");
//Append <li> to <ul> as child
menuUL.appendChild(menuULitem);
//Create <a> tag element
menuAtag = document.createElement("a");
//Append <a> to <li> as child
menuULitem.appendChild(menuAtag);
//Set the <a> href attribute to point to the anchor tag in body of document
menuAtag.setAttribute("href", "#item" + i)
//Append link text as a hchild of <a>
var menuText = document.createTextNode(linkText);
menuAtag.appendChild(menuText);
//Create an anchor point for each <h2>
var anchor = document.createElement("a");
//Set anchor attribute name
anchor.setAttribute("name", "item" + i);
//Insert anchor in to DOM
document.body.insertBefore(anchor, headings[i]);
//Give headings a class attribute
headings[i].setAttribute("class", "heading2");
}
//Insert the Menu created in above loop in to the DOM
document.body.insertBefore(menu, document.body.firstChild);
//change <h2> on mouseover/mouseout
document.getElementsByClassName("heading2").onmouseover.style.color="red";
}//close function (dynamicMenu)
window.onload = dynamicMenu;
Share
Improve this question
asked Jul 3, 2015 at 19:41
Maurice GreenlandMaurice Greenland
3152 gold badges5 silver badges20 bronze badges
2
-
2
You can't just use CSS for this?
.heading2:hover {color:red;}
– Rhumborl Commented Jul 3, 2015 at 19:45 - I know I could use css, but I'm trying to find how to do it with javascript – Maurice Greenland Commented Jul 4, 2015 at 9:41
5 Answers
Reset to default 4Use CSS
h2:hover
{
color : red;
}
if you don't need to remove color when mouse moves out use
var headers = document.getElementsByTagName("h2");
for (var i in headers)
{
headers[i].onmouseover = function()
{
this.style.color = 'red';
}
}
You can do it like this:
<h2 id="heading2" onmouseover="myFunction()">The Heading</h2>
<script>
function myFunction() {
document.getElementById("heading2").style.color = "red";
};
</script>
Or you can do it like this:
<h2 onmouseover="this.style.color = 'red'">The Heading</h2>
Wouldn't it be easier to use jquery. You can just do something like:$("h2").hover(function() {
$("h2").css(color:"red);
});
At the end of your function with native javascript :
var tags = document.getElementsByClassName("heading2");
// For each tag we add an event listener
for (var i=0;i<tags.length;i++){
tags[i].onmouseover = mouseIn;
tags[i].onmouseout = mouseOut;
}
function mouseIn (element) {
element.target.style.color = "red";
}
function mouseOut (element) {
element.target.style.color = "inherit";
}
Better (with jquery), add this at <head>
tag:
<script src="http://code.jquery./jquery-latest.js"></script>
So in the bottom of your page or other .js :
// Add event with event delegation
// (does not care about add new .heading2 elements
// and only an event is asigned to 'body' tag
$('body').on('mouseover', '.heading2' ,function(){ $(this).css({"color":"red"}); });
$('body').on('mouseout', '.heading2' ,function(){ $(this).css({"color":"inherit"}); });
... better and easiest! (simpliest css) :
In your .css style:
.heading2:hover {
color: 'red';
}
Your current syntax is not valid Javascript code.
What you are trying to achieve can be pleted using one of the following Javascript syntactical options:
// Option 1: Event Listener
document.getElementsByClassName("heading2")[0].addEventListener("mouseover",
function() {
this.style.color = "red";
}, true);
// Option 2: Element Method
document.getElementsByClassName("heading2")[0].onmouseover = function() {
this.style.color = "red";
};
// Option 3: HTML Activation
<script>
function setColor() {
this.style.color = "red";
}
</script>
<h2 class="heading2" onmouseover="setColor()"></h2>
Of course you could also resort to the more simple CSS option:
h2.heading2:hover {
color: red;
}
... Or a Javascript library such as JQuery
.