I have 1,000 links on one page. Each link has a title/note/tool-tip. All the titles say the same thing so rather than typing it up on each line is there a way that I can have javscript do this for me?
Example Before:
<div class="links">
<a href="#" title="This is a title">Tooltips</a>
<a href="#" title="This is a title">Tooltips</a>
<a href="#" title="This is a title">Tooltips</a>
<a href="#" title="This is a title">Tooltips</a>
</div>
Example of what I would like:
<div class="links">
<a href="#" >Tooltips</a>
<a href="#" >Tooltips</a>
<a href="#" >Tooltips</a>
<a href="#" >Tooltips</a>
</div>
and have java script display a note when mouseover of "div .links a"
Thanks in advance.
var set = document.querySelectorAll(".links a");
var tip = document.createElement("div");
tip.className = "hover";
var msg = document.createElement("div");
tip.appendChild(msg);
msg.innerHTML = "Generic Hover Message";
for( var i = 0, n = set.length; i < n; i++ ){
set[i].onmouseover = function(){
this.parentNode.insertBefore(tip,this);
};
set[i].onmouseout = function(){
tip.parentNode.removeChild(tip);
};
}
Set up events for the target elements
Use a combination of document.querySelectorAll MDN and iterate through the set assigning the onmouseover event MDN and onmousout event MDN to each element.
var set = document.querySelectorAll(".links a");
for( var i = 0, n = set.length; i < n; i++ ){
set[i].onmouseover = function(){
Create an element using document.createElement MDN for the tooltip
var tip = document.createElement("div");
tip.className = "hover";
var msg = document.createElement("div");
tip.appendChild(msg);
msg.innerHTML = "Generic Hover Message";
Create styling to position the tooltip
.hover{
position: absolute;
display:inline-block;
width:100%;
}
.hover > div{
top: 1.2em;
position:absolute;
z-index: 1;
}
Use insertBefore MDN to place the element
this.parentNode.insertBefore(tip,this);
Like this?
<div class="links" title="This is a title">
<a href="#" >Tooltips</a>
...
Here is an example using Travis' proposed solution with a querySelector and onmouseover.
<html>
<head>
<title>Link over</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<style>
.links{
}
</style>
<script>
// I show a tooltip
function showTip() {
console.log("I'm a tooltip");
}
// I set up the listeners
window.onload = function() {
var links = document.querySelector("div.links");
for (var i = 0; i < links.children.length; i++) {
links.children[i].onmouseover = showTip;
}
};
</script>
</head>
<body>
<div class="links">
<a href="#">Tooltips</a>
<a href="#">Tooltips</a>
<a href="#">Tooltips</a>
<a href="#">Tooltips</a>
</div>
</body>
</html>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.