How to use the jQuery Selector in this web application? - javascript

I am trying to work out to select a delete icon in my own web application. delectIcon
HTML
<main>
<div class="container">
<div class="tabs">
<p><span class="active">Newest</span></p><a href=""><p>
<span>Oldest</span></p></a><p><span>Add</span></p>
</div>
<div class="content">
<ul>
<li>
<span class="itemLeft">Answer emails</span>
<span class="itemMiddle">12-31-2016</span>
<span class="itemRight">1</span>
<b class="deleteIcon"> X </b>
</li>
<li>
<span class="itemLeft">Prep for Monday's class</span>
<span class="itemMiddle">12-31-2016</span>
<span class="itemRight">5</span>
<b class="deleteIcon"> X </b>
</li>
</ul>
</div>
</div>
</main>
JavaScript
$(".deleteIcon").on("click", function () {
alert("Oh, clicked!");
return false;
});
I failed to do so by writing it myself. So I used Chrome Web Developer Tool to find the CSS path. I tried to use the XPath($"[/html/body/main/div/div[2]/ul/li[ 1 ]/b]") and CSS Path ($"(pathbody > main > div > div.content > ul > li:nth-child(1) > b)"). Neither of them worked.
I tried to mark it with an ID and made only one "li" exists. The CSS selector worked all right. But when I clicked the deleteIcon$"(#deleteIcon)", nothing happened.
#deleteIcon{
float:right;
font-weight: bold;
padding: 0 3px 0 3px;
border-radius: 5px;
background: #ccc;
cursor: pointer;
margin-left: 5px;
font-size: 1.3em;
text-align: center;
}
I also tried to select my title. I found the following worked out.
$(".container h1").on("click", function () {
alert("Oh, no!");
return false;
});
I do not what to do now. Can anyone help me out here?
Thank you! I would be really appreciate if you can answer my question.
Adding more details:
I did actually add the deleteIcon into the HTML by JavaScript. I do not know whether this can have an effect on my selector.
Actual HTML
<main>
<div class="container">
<div class="tabs">
<p><span class="active">Newest</span></p><a href=""><p>
<span>Oldest</span></p></a><p><span>Add</span></p>
</div>
<div class="content">
</div>
</div>
</main>
JavaScript (The important part listed below)
function Item(name,dueDate,type){
this.name=name;//1
this.dueDate=dueDate;//input2
this.type=type;//3
};
$(".tabs a span").toArray().forEach(function (element) {
var $element = $(element);
// create a click handler for this element
$element.on("click", function () {
var $content,
$input,
$button,
i;
if ($element.parent().parent().is(":nth-child(1)")) {
// newest first, so we have to go through
// the array backwards
$content = $("<ul>");
for (i = Task.length-1; i >= 1; i--) {
// $buttondelete = $("<buttonDelete>").text("X");
var txt1 = Task[i].toStringName();
var txt2 = Task[i].toStringDate();
var txt3 = Task[i].toStringType();
//alert(txt3);
$content.append('<li> <span class="itemLeft">'+txt1+'</span> <span class="itemMiddle">'+txt2+'</span> <span class="itemRight">'+txt3+'</span><b class="deleteIcon"> X </b>');
}
}
$("main .content").append($content);
return false;
});
});

If you are creating the items inside ul dynamically you should bind the click event like this :
$(".content").on("click", ".deleteIcon", function()
{
alert("clicked") ;
return false;
}
) ;

The class selector starts with a . (just like the example you say you have that works).
Try
$(".deleteIcon").on("click", function () {
alert("Oh, clicked!");
return false;
});

Related

Why is my .focus() going to the beginning of my `contenteditable` `div`?

I am creating a book writing website, mostly in php. I have a jQuery function that when the "New Chapter" button is clicked triggers an AJAX function as well as some other JS/jQuery events. Part of those events is that it should focus() my cursor to the END of the <div> and then focus the cursor to the end of it.
For whatever reason, after it appends the information, it moves my cursor to the beginning of the <div>
HTML
<section>
<aside>
<h3>Table of Contents</h3>
<ul id='toc_base'><?php json_toc($meta); ?></ul>
</aside>
<article>
<div contenteditable='false' id='metadata'>
<?php
$bookTitle = htmlspecialchars($bookTitle);
$author = htmlspecialchars($meta->book->metadata->author);
$startyear = htmlspecialchars($meta->book->metadata->startyear);
$isbn = ($meta->book->metadata->isbn != "" && $meta->book->metadata->isbn != null)
? htmlspecialchars($meta->book->metadata->isbn)
: "Not Listed";
$endyear = ($meta->book->metadata->endyear != "" && $meta->book->metadata->endyear != null)
? htmlspecialchars($meta->book->metadata->endyear)
: "TBD";
echo "Title: $bookTitle | Written By: $author | ISBN: $isbn<br />Start Year: $startyear | End Year: $endyear";
?>
</div>
<nav style='grid-column: 1 / span 10'>
<button style='font-weight:bold' id='bold'>B</button>
<button style='font-style:italic' id='italic'>I</button>
<button style='text-decoration:underline' id='underline'>U</button>
<!-- BUTTON IS HERE -->
<button style='font-weight:bold' onclick='addChapter()'>Chapter Title</button>
<!-- BUTTON ENDS HERE -->
<button class='tooltip'>
<i class="fa-sharp fa-solid fa-person-circle-plus"></i>
<span class='tooltiptext'>Add new character to the panel on the right.</span>
</button>
<button class='tooltip' onclick='autosave()'>
<i class="fa-sharp fa-solid fa-floppy-disk"></i>
<span class='tooltiptext'>Be like Jesus - Save!</span>
</button>
<button class='tooltip'>
<i class="fa-sharp fa-solid fa-database"></i>
<span class="tooltiptext">Edit metadata such as author information, and ISBN.</span>
</button>
<div id='update'>...Saved...</div>
</nav>
<!-- CONTENT IS HERE -->
<div contenteditable='true' id='content' type='text' autocomplete='off'></div>
<!-- CONTENT ENDS HERE -->
</article>
<aside>
<h3>Characters</h3>
<ul id='char_base'><?php json_characters($meta); ?></ul>
</aside>
</section>
jQuery and JS
function addChapter() {
var end;
let chapter = prompt("New Chapter Name?");
if (chapter != null) {
$.get("editor.php?newchapter=" + chapter, function (data, status) {
$("#toc_base").html("<li>" + chapter + "</li>");
$("#content").append("[b]" + chapter + "[/b]\n\n");
var div = document.getElementById('content');
div.focus();
});
}
}
Errors/Exceptions
There are no errors or exceptions displayed on the page or the console_log.
What I've Done
I did check a number of SO questions and all of them seemed to say to just use focus(), which, I have (in many different ways). I've tried it in a timeout function, which did the exact same thing as above. I did it in jQuery: $("#update").focus(); and there was no difference.
Browser
Chrome Version 107.0.5304.62 (Official Build) (64-bit)
What I'm Hoping to Avoid
I'd like to avoid using textarea if possible. All the extra white-space it has the potential to create when using php is just annoying. I can do it if necessary, but I'd like to stay away from it.
SMALL CHANGE TO WHAT'S HAPPENING
If I were to manually move the cursor to the end after one input of the chapter title, then add a second, it focuses at the beginning of the most recent append.
I've given up on trying to get <div contenteditable='true'> to do what I want. I've changed it to <textarea> - I then updated my jQuery:
function addChapter() {
let chapter = prompt("New Chapter Name?");
if (chapter != null) {
let temp = $("#content").val();
$("#toc_base").append("<li>" + chapter + "</li>");
$("#content").val(temp + "[b]" + chapter + "[/b]\r\n\r\n");
$.get("editor.php?newchapter=" + chapter, function (data, status) { });
}
$("#content").focus();
}
This does appear to do what I want. I'm not happy that I need to save all the text to a var and then set the val() to the original + new.
If anyone has any ways to do this better, or with the <div> that I originally had, please let me know.
I was finally able to figure out how to do this...
HTML/PHP
<div id='content_container_1'>
<div id='content_container_2'>
<div contenteditable="true" id='content'><?php echo $book->content->writing; ?></div>
</div>
</div>
CSS
#content_container_1 {
height:80vh;
width: 100%;
overflow:auto;
border: 1px solid black;
background-color: white;
}
#content_container_2 {
min-height:100%;
display:table;
}
#content {
width:273px;
font-size: 18px;
font-weight: normal;
line-height: 18px;
outline: none;
vertical-align: middle;
display: table-cell;
position: relative;
-webkit-user-select: text;
-moz-user-select: text;
-ms-user-select: text;
user-select: text;
word-wrap: break-word;
overflow:hidden;
}
JS
$(document).ready(function () {
$("#content").focus(); /** <---- This part ---->
setInterval(autosave, 30000); //ignore
$("#update").removeClass("visible"); //ignore
});

How do I check whether an element is already bound to an event?

Goal
Avoid unnecessary event bindings.
Sample code
Comment box with a reply button for each individual comment
const btns = document.getElementsByClassName('reply-btn');
for (let i = 0; i < btns.length; i++) {
btns[i].addEventListener('click', showCommentContentAsPreview);
}
function showCommentContentAsPreview(e) {
console.log('showCommentContentAsPreview()');
// CHECK IF THIS BUTTON ALREADY BINDED !!!
const previewDiv = document.getElementById('preview');
const commentId = e.target.getAttribute('data-comment-id')
const commentDiv = document.getElementById('comment-' + commentId);
const commentText = commentDiv.querySelector('p').innerText
const closeReplyBtn = previewDiv.querySelector('button');
const previewContent = previewDiv.querySelector('.preview-content');
// set to preview
previewContent.innerText = commentText;
// show reply close button
closeReplyBtn.classList.remove('hidden');
// bind EventListener to "reply close button"
closeReplyBtn.addEventListener('click', closeReply)
function closeReply() {
console.log('bind to btn');
previewContent.innerText = '';
this.removeEventListener('click', closeReply);
closeReplyBtn.classList.add('hidden');
}
}
.hidden {
display: none;
}
.comment {
border-bottom: 1px solid #000;
padding: 5px;
}
.preview {
background-color: #ccc;
padding: 20px;
margin-top: 20px;
}
<div>
<!-- comment list -->
<div id="comment-1" class="comment">
<p>Comment Content 1</p>
<button class="reply-btn" data-comment-id="1">reply</button>
</div>
<div id="comment-2" class="comment">
<p>Comment Content 2</p>
<button class="reply-btn" data-comment-id="2">reply</button>
</div>
</div>
<!-- output -->
<div>
<div id="preview" class="preview">
<div class="preview-content"></div>
<button class="hidden">Close Preview</button>
</div>
</div>
Simulate problem
When you try the example, the following two scenarios occur:
Click reply once and then click "close preview"
Click on reply several times and then on "close preview".
Question
How can I avoid multiple bindings to the same button? I am already thinking about singleton.
Instead of binding a listener to every element in the series, you can bind a single listener once on a common parent of them all, and then use element.matches() to determine if the click target is the one that you want before doing more work. See the following example:
function logTextContent (elm) {
console.log(elm.textContent);
}
function handleClick (ev) {
if (ev.target.matches('.item')) {
logTextContent(ev.target);
}
}
document.querySelector('ul.list').addEventListener('click', handleClick);
<ul class="list">
<li class="item">Item 1</li>
<li class="item">Item 2</li>
<li class="item">Item 3</li>
<li class="item">Item 4</li>
<li class="item">Item 5</li>
</ul>
With the helpful hints from #Zephyr and #jsejcksn I have rewritten the code of the above question. Thus I have achieved my goal of avoiding multiple identical bindings to one element.
const container = document.getElementById('comment-container');
const previewDiv = document.getElementById('preview');
const closeReplyBtn = previewDiv.querySelector('button');
const previewContent = previewDiv.querySelector('.preview-content');
container.addEventListener('click', handleClick);
function handleClick(ev) {
if (ev.target.matches('.reply-btn')) {
if (ev.target.getAttribute('listener') !== 'true') {
removeOtherListenerFlags();
ev.target.setAttribute('listener', 'true');
showCommentContentAsPreview(ev);
}
}
if (ev.target.matches('#preview button')) {
previewContent.innerText = '';
closeReplyBtn.classList.add('hidden');
removeOtherListenerFlags();
}
}
function showCommentContentAsPreview(e) {
console.log('showCommentContentAsPreview()');
const commentId = e.target.getAttribute('data-comment-id')
const commentDiv = document.getElementById('comment-' + commentId);
const commentText = commentDiv.querySelector('p').innerText
// set to preview
previewContent.innerText = commentText;
// show reply close button
closeReplyBtn.classList.remove('hidden');
}
function removeOtherListenerFlags() {
const replyBtns = container.querySelectorAll('.reply-btn')
Object.keys(replyBtns).forEach((el) => {
replyBtns[el].removeAttribute('listener');
})
}
.hidden {
display: none;
}
.comment {
border-bottom: 1px solid #000;
padding: 5px;
}
.preview {
background-color: #ccc;
padding: 20px;
margin-top: 20px;
}
<div id="comment-container">
<div id="comment-listing">
<!-- comment list -->
<div id="comment-1" class="comment">
<p>Comment Content 1</p>
<button class="reply-btn" data-comment-id="1">reply 1</button>
</div>
<div id="comment-2" class="comment">
<p>Comment Content 2</p>
<button class="reply-btn" data-comment-id="2">reply 2</button>
</div>
</div>
<!-- output -->
<div>
<div id="preview" class="preview">
<div class="preview-content"></div>
<button class="hidden">Close Preview</button>
</div>
</div>
</div>
Cool and Thanks!

Show and hide divs with JS

I have 5 <a>...
<a id="showtrips">TRIPS</a>
<a id="showeats">EATS</a>
<a id="showfilms">FILMS</a>
<a id="showmusic">MUSIC</a>
<a id="showtravels">TRAVELS</a>
...and I have 5 <div> and each div have the content of the <a> names. I want show all <a> and show only a <div>, so I want click on a <a> and hide the others divs showing only the selected div.
I'm searching and searching but I can´t find this exactly I found similar things but impossible to integrate to this problem.
This are the divs tags
<div id="trips">Content Trips</div>
<div id="eats">Content Eats</div>
<div id="films">Content Films</div>
<div id="music">Content Music</div>
<div id="travels">Content Travels</div>
#trips{ display: block };
#eats{ display: none };
#films{ display: none };
#music{ display: none };
#travels{ display: none };
This should do it, though this hides all divs on click, apart from the div matching the a tag. I'd suggest adding something to identify the divs to show/hide. This only requires vanilla js.
const test = document
.querySelectorAll('[id*="show"]')
.forEach(element => element.onclick = () => {
document
.querySelectorAll('div')
.forEach(element => {
element.style.display = 'none';
});
const divIdToShow = element.id.replace('show', '');
const divElementToShow = document.getElementById(divIdToShow);
divElementToShow.style.display = 'block';
});
console.log(test)
#trips {
display: block;
}
#eats {
display: none;
}
#films {
display: none;
}
#music {
display: none;
}
#travels {
display: none;
}
<a id="showtrips">TRIPS</a>
<a id="showeats">EATS</a>
<a id="showfilms">FILMS</a>
<a id="showmusic">MUSIC</a>
<a id="showtravels">TRAVELS</a>
<div id="trips">Content Trips</div>
<div id="eats">Content Eats</div>
<div id="films">Content Films</div>
<div id="music">Content Music</div>
<div id="travels">Content Travels</div>
This is trivial. You have 2 options: either add "onclick" events on each of your tags and then listen to these events with js. Or, since you added ids to each of your tags, you can now attach click events to them with js.
So, no more words. Here's the simple solution:
document.getElementById("showtrips").onclick = toggleShowForElement(document.getElementById("trips"));
document.getElementById("showeats").onclick = toggleShowForElement(document.getElementById("eats"));
document.getElementById("showfilms").onclick = toggleShowForElement(document.getElementById("films"));
document.getElementById("showmusic").onclick = toggleShowForElement(document.getElementById("music"));
document.getElementById("showtravels").onclick = toggleShowForElement(document.getElementById("travels"));
function toggleShowForElement(element) {
return () => {
if (element.style.display === "none") {
element.style.display = "block";
} else {
element.style.display = "none";
}
}
}
body {
font-family: "Verdana", sans-serif;
}
* {
box-sizing: border-box;
}
a {
cursor: pointer;
color: #008800;
display: inline-block;
padding: 4px;
border-radius: 4px;
}
a:hover {
text-decoration: underline;
}
div {
background-color: #88DD99;
border-radius: 4px;
padding: 5px;
margin-bottom: 5px;
height: 30px;
text-align: center;
}
<a id="showtrips">TRIPS</a>
<a id="showeats">EATS</a>
<a id="showfilms">FILMS</a>
<a id="showmusic">MUSIC</a>
<a id="showtravels">TRAVELS</a>
<div id="trips">Content Trips</div>
<div id="eats">Content Eats</div>
<div id="films">Content Films</div>
<div id="music">Content Music</div>
<div id="travels">Content Travels</div>
Just added a bit of CSS to make it look a bit prettier. It's not needed here.
If you are using simple javascript you can toggle the div using the following code:
var mydiv = document.getElementById("myDIV");
if (mydiv.style.display === "none") {
mydiv.style.display = "block";
} else {
mydiv.style.display = "none";
}
If you using jQuery you can directly use toggle methods.
$( ".target" ).toggle();
I suggest you group your div and anchor tags using the class name, So it will be easy to maintain.
Your html code will be like:
<a id="showtrips" class="link">TRIPS</a>
<a id="showeats" class="link">EATS</a>
<a id="showfilms" class="link">FILMS</a>
<a id="showmusic" class="link">MUSIC</a>
<a id="showtravels" class="link">TRAVELS</a>
<div id="trips" class="content">Content Trips</div>
<div id="eats" class="content">Content Eats</div>
<div id="films" class="content">Content Films</div>
<div id="music" class="content">Content Music</div>
<div id="travels" class="content">Content Travels</div>
Your JS code will be look like:
document
.querySelectorAll('[class="link"]')
.forEach(element => element.onclick = () => {
document
.querySelectorAll('[class="content"]')
.forEach(element => {
element.style.display = 'none';
});
const mydiv = element.id.substr(4);
document.getElementById(mydiv).style.display = 'block';
});
I just created the working jsfiddle for you link here

Javascript on click event for multiple buttons with same class

I have a few buttons across a site I am building, certain buttons have one class while others have another. What I am trying to do is find the best way to find the clicked button without having an event listener for each individual button. I have come up with the below 2 for loops to find all the buttons with class button-1 and class button-2. Being fairly new to javascript i just don't want to get into bad habits so would appreciate any advice on the best way to achieve this.
<section>
<div class="button--1"></div>
<div class="button--1"></div>
<div class="button--2"></div>
</section>
<section>
<div class="button--2"></div>
<div class="button--1"></div>
<div class="button--2"></div>
</section>
var button1 = document.querySelectorAll('.button--1');
var button2 = document.querySelectorAll('.button--2');
for (var a = 0; a < button1.length; a++) {
button1[a].addEventListener('click',function(){
//do something
});
}
for (var b = 0; b < button2.length; b++) {
button1[b].addEventListener('click',function(){
//do something
});
}
If you plan to have multiple other classes like button--3, …4 … …15,
You must want to target all div elements which class starts (^=) with "button":
(Note that you can do it in the CSS too!)
var allButtons = document.querySelectorAll('div[class^=button]');
console.log("Found", allButtons.length, "div which class starts with “button”.");
for (var i = 0; i < allButtons.length; i++) {
allButtons[i].addEventListener('click', function() {
console.clear();
console.log("You clicked:", this.innerHTML);
});
}
/* Some styling */
section {
margin: 8px 0;
border: 1px solid gray;
}
section div {
border: 1px solid lightgray;
display: inline-block;
margin-left: 8px;
padding: 4px 8px;
width: 30px;
}
section div[class^=button] {
background: lightgray;
cursor: pointer;
}
<span>You can click on the buttons:</span>
<section>
<div class="button--1">s1-1</div>
<div class="button--2">s1-2</div>
<div class="button--3">s1-3</div>
<div class="button--4">s1-4</div>
</section>
<section>
<div class="button--1">s2-1</div>
<div class="button--2">s2-2</div>
<div class="button--3">s2-3</div>
<div class="button--4">s2-4</div>
</section>
<section>
<div class="not-a-button">not1</div>
<div class="not-a-button">not2</div>
<div class="not-a-button">not3</div>
<div class="not-a-button">not4</div>
</section>
Hope it helps.
Try using event delegation
(function() {
document.body.addEventListener("click", clickButtons);
// ^ one handler for all clicks
function clickButtons(evt) {
const from = evt.target;
console.clear();
if (!from.className || !/button--\d/i.test(from.className)) { return; }
// ^check if the element clicked is one of the elements you want to handle
// if it's not one of the 'buttons', do nothing
console.log("you clicked " + from.classList);
}
}())
.button--1:before,
.button--2:before {
content: 'BTTN['attr(class)']';
}
.button--1,
.button--2 {
border: 1px solid #999;
background: #eee;
width: 220px;
padding: 3px;
text-align: center;
}
<section>
<div class="b1 button--1 section1"></div>
<div class="b2 button--1 section1"></div>
<div class="b3 button--2 section1"></div>
</section>
<section>
<div class="b4 button--2 section2"></div>
<div class="b5 button--1 section2"></div>
<div class="b6 button--2 section2"></div>
</section>
You can use multiple selectors in the string of querySelctorAll() by separating them with a ,
var button1 = document.querySelectorAll('.button--1');
var button2 = document.querySelectorAll('.button--2');
var allButtons = document.querySelectorAll('.button--1, .button--2');
console.log(button1.length);
console.log(button2.length);
console.log(allButtons.length);
<section>
<div class="button--1"></div>
<div class="button--1"></div>
<div class="button--2"></div>
</section>
<section>
<div class="button--2"></div>
<div class="button--1"></div>
<div class="button--2"></div>
</section>
My suggestion is to use jQuery so that you can do it something like this:
$(document).on('click', '.button--1', function() {
// Do something
});
$(document).on('click', '.button--1', function() {
// Do something
})
But a clean approach for pure Javascript is to create a function that binds a callback for the event.
function bindEvent(callback, eventType, targets) {
targets.forEach(function(target) {
target.addEventListener(eventType, callback);
});
};
var button1 = document.querySelectorAll('.button--1');
var button2 = document.querySelectorAll('.button--2');
bindEvent(function() {
// do something
}, 'click', button1);
bindEvent(function() {
// do something
}, 'click', button2);
The click event is fired when a pointing device button (usually a mouse's primary button) is pressed and released on a single element.
This documentation will help you to understand how it works MDN - Click event

Generic Javascript Code

I wrote a code for a hover functionality. Now, I am asking myself how to make this code generic in order to show different divs when hovering over a different link. The JavaScript code is as follows:
<script>
$(function() {
var moveLeft = 20;
var moveDown = 10;
$('a#trigger').hover(function(e) {
$('div#purpose').show();
}, function() {
$('div#purpose').hide();
});
$('a#trigger').mousemove(function(e) {
$("div#purpose").css('top', e.pageY + moveDown).css('left', e.pageX + moveLeft);
});
});
</script>
The div I call is as follows:
<!-- Purpose: Hover Popup -->
<div class= id="purpose">
<h3>Purpose</h3>
<p>
Test
</p>
</div>
Furthermore, I added some CSS style
<!-- Style for Hovering -->
<style type="text/css">
div#purpose {
display: none;
position: absolute;
width: 280px;
padding: 10px;
background: #eeeeee;
color: #000000;
border: 1px solid #1a1a1a;
font-size: 90%;
}
</style>
Could anybody tell me how to make this code generic in order to add further divs which are called from another link?
Create a javascript function and pass in the variables (e.g. link and div)
function foo($link, $div){
var moveLeft = 20;
var moveDown = 10;
$link.hover(function(e) {
$div.show();
}, function() {
$div.hide();
});
$link.mousemove(function(e) {
$div.css('top', e.pageY + moveDown).css('left', e.pageX + moveLeft);
});
}
For your existing behaviour call the following for example:
foo($('a#trigger'), $("div#purpose"));
This will actually be slightly better for performance as you'll be using the same jQuery reference each time. However depending on how you're actually planning on using this, having a seperate function call each time might not be the best way.
For example if you wish to use this on dynamic data it wouldn't be sensible to make static calls to a function each time.
Make use of custom data-* attributes in your HTML, and use classes to target a generalized group of elements, ex:
<a class="trigger" data-target="purpose" />
And the JS
$(".trigger").hover(function(e) {
var elemToShow = $(this).data("target");
$("#" + elemToShow).show();
}, function() {
var elemToShow = $(this).data("target");
$("#" + elemToShow).show();
}).mousemove(function(e) {
var elemToShow = $(this).data("target");
$("#" + elemToShow).css('top', e.pageY + moveDown).css('left', e.pageX + moveLeft);
});
You could build your trigger elements in a way that they hold the information about what element to show:
<a class="trigger" data-show="purpose">...</a>
Then you initialize them all at once like this:
$(function() {
$('.trigger').hover(function() {
var elementId = $(this).data('show');
$('#'+elementId).show();
}, function() {
var elementId = $(this).data('show');
$('#'+elementId).hide();
);
});
You don't need any JavaScript or jQuery at all for this--you can simply use CSS with the :hover pseudo-class.
.menu {
background-color: #eee;
}
.menuItem {
display: inline-block;
}
.menu .trigger + .purpose {
display: none;
position: absolute;
background-color: #eee;
}
.menu .trigger:hover + .purpose, .menu .trigger + .purpose:hover {
display: block;
}
<div class="menu">
<div class="menuItem">
Trigger 1
<div class="purpose">
<h3>Purpose 1</h3>
<p>
Test 1
</p>
</div>
</div>
<div class="menuItem">
Trigger 2
<div class="purpose">
<h3>Purpose 2</h3>
<p>
Test 2
</p>
</div>
</div>
<div class="menuItem">
Trigger 3
<div class="purpose">
<h3>Purpose 3</h3>
<p>
Test 3
</p>
</div>
</div>
<div class="menuItem">
Trigger 4
<div class="purpose">
<h3>Purpose 4</h3>
<p>
Test 4
</p>
</div>
</div>
</div>

Categories

Resources