Advanced sibling selector [duplicate] - javascript

This question already has answers here:
How do I select an element based on the state of another element in the page with CSS?
(3 answers)
Closed 7 years ago.
I can't quite get my head around this. I have the following construct:
<div class="container">
for n = 0 to ...
Link n
endfor
for each link in ".container"
<div class="poptip"></div>
endfor
</div>
And an example could be:
<div class="container">
Link 1
Link 2
Link 3
<div class="poptip">Some content related to link 1 retreived with ajax</div>
<div class="poptip">...</div>
<div class="poptip">...</div>
</div>
Now the hurdle, I am trying to show the .poptip on hover on the anchor tag, and this obviously works fine if there is one link (which is usually the case). In any case where there's >1 link, then the last one will work. Current css (sass style) which doesn't quite work in >1 cases:
.producttooltip {
position: relative;
}
.producttooltip a:hover + div {
display: block;
}
I cannot change the structure of the html, it will always be container > all links followed by all poptips. I can however mark the poptips and anchor tags up with unique identifiers e.g. Link 1<div class="poptip" rel="identifier"></div>, but I can't quite figure out if I in css can create a general selector which goes (pseudo):
a:hover + div[rel=a.rel] {
display: block
}
So my question is, can I get this construct marked up in pure CSS, or do I have to use some JS trickery (which I can, but I would really prefer CSS). Hope one of you guys are more clever than me.
Edit: just gonna clarify - I cannot change the structure of the html. The neatest solution would obviously be to wrap each element with it's equivalent poptip, but my entire conundrum is the fact that I cannot do this.

In your case, you can do this way:
$('a').on('hover', function() {
$('.poptip').eq($(this).index()).show();
}, function() {
$('.poptip:visible').hide();
});
It is tough to do this with CSS alone. But even then, I have provided a CSS solution below. Do have a look if you wanna consider a CSS only solution.
You can do this via CSS itself. Although there are lot of plugins, lets do something like this. First, you need a hovering element, say in this case, a link.
Hover Me!
Next should be the tool tip. We can have a <span> for now and put it inside the link.
Hover Me!<span class="tooltip">Hello, World!</span>
Now comes the real CSS part.
a span {display: none; position: absolute; color: #fff; background: #000; padding: 5px;}
a {position: relative;}
a:hover span {display: block; text-align: center;}
Snippet
a span {display: none; position: absolute; color: #fff; background: #000; padding: 5px;}
a {position: relative;}
a:hover span {display: block; text-align: center;}
Hover Me!<span class="tooltip">Hello, World!</span>
This is just one of a pure CSS solution. You can see the working fiddle here.
However, there are a lot of plugins, which keep this concept as base and work for hover-cards and tool tips. Some good examples include:
jQuery UI Tooltip
Tipsy
HoverCard
40+ Tooltips Scripts With AJAX, JavaScript & CSS

jQuery solution
You can use mouseenter/mouseleave event in order to show up the desired elements
$('a').on('mouseenter', function() {
var i = $(this).index();
$('.poptip').eq(i).show();
}).on('mouseleave', function() {
$('.poptip').hide();
});
.poptip {
width:100%;
float:left;
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="container">
Link 1
Link 2
Link 3
<div class="poptip">Some content related to link 1 retreived with ajax</div>
<div class="poptip">Some content related to link 2 retreived with ajax</div>
<div class="poptip">Some content related to link 3 retreived with ajax</div>
</div>

Using jquery this can be achieved easily, just need to get the index of the current anchor element & display the respective div present at the index location.
HTML CODE:
<div class="container">
Link 1
Link 2
Link 3
<div class="poptip">Some content related to link 1 retreived with ajax</div>
<div class="poptip">...</div>
<div class="poptip">...</div>
</div>
JS CODE:
$(function(){
$('a').on('hover',function(){
var ind = $('a').index(this);
$('.poptip').eq(ind).css('display','block');
});
});
Live Demo # JSFiddle

Related

When using the data-list element is there a way to show tool-tips for each option

So I currently Have a data list full of different abilities for a game is there any way to make it so when you hover over each ability it will give a tooltip saying what the ability is? It doesn't have to be a tooltip just something that functions similarly, a iframe would work if you have a smart idea on how to do it!
here is the website: https://mindweavedmstation.hunterscott1.repl.co/
if you click the edit button(right under ability), then it will show up with three + buttons press the one under abilities, this will create a new box if you click in this box it will show the data list of abilities. I would like for as you hover over a ability a box will pop up to the right explaining the ability.
here is a link to the code: https://repl.it/#HunterScott1/MindWeaveDMStation#index.html
The data list can be found at script.js line 108
If you have any clarifying questions feel free to ask!
Thank you!
The question is how to add some onhover action to an HTML option tag in a datalist element.
The immediate answer is that you can't. You can't even style the individual options (though some browsers let you a little this is not standardised), let alone instigate some action onhover.
There are some workarounds:
Automatically replace all such elements
You can introduce some Javascript which scans through your document, finds e.g. droplist or select elements, sets them not to display, and adds alongside them 'standard' elements like divs which emulate them. You can see further discussion on this for example at How to style the option of an html "select" element?
Although this might be useful, for example if you do not have complete control of all the source code, it adds a layer of complexity which isn't necessary if you can implement the HTML yourself.
If you control the HTML, implementing your own options drop down is not very complex and has the added advantage that you can style things the way you want them to match the rest of your site, not rely on the (inconsistent) styling of such lists across browsers.
Here's some code to get you started. Add CSS to the elements as you like:
<head>
<style>
.select {
background-color: white;
width: 300px;
height: auto;
font-size: 16px;
border-style: solid;
padding: 10px;
}
.options {
display: none;
}
.option {
width: 100%;
height: 40px;
background-color: white;
}
.hoverinfo {
display: none;
float: right;
background-color: #eeeeee;;
}
ul {
list-style: none;
}
</style>
</head>
<body onclick="document.getElementById('select').firstElementChild.style.display='none';">
<div id="select" class="select" onclick="event.preventDefault();event.stopPropagation();this. firstElementChild.style.display='block';">
Select from this list
<ul class="options">
<li class="option" onclick="userhaschosen(this);" onmouseenter="event.preventDefault();event.stopPropagation();this.firstElementChild.style.display='block';" onmouseout="event.preventDefault();event.stopPropagation();this.firstElementChild.style.display='none';">
Option 1
<div class="hoverinfo">info about this option</div>
</li>
<li class="option" <li class="option" onclick="userhaschosen(this);" onmouseenter="event.preventDefault();event.stopPropagation();this.firstElementChild.style.display='block';" onmouseout="event.preventDefault();event.stopPropagation();this.firstElementChild.style.display='none';">
Option 2
<div class="hoverinfo">info about this option</div>
</li>
</ul>
</div>
<script>
function userhaschosen(el) {
event.preventDefault();
event.stopPropagation();
el.parentElement.style.display='none';
alert("user has chosen option "+el.firstChild.textContent);//instead of this alert, do whatever it is you want to do when the user has clicked an option
}
</script>
</div>

How to target only current hovered element in Vanilla Javascript

I am building a web page for homework. I am trying to figure out how to make a child div appear whenever I hover over the parent div at the bottom, sort of like a dropdown menu. The thing is that the child div has a class and I want only the element that is hovered to show the child div from the parent div. More specifically, the parent div I am talking about is <div class="inside-box" onMouseOver="showDDContent();" onMouseOut="hideDDContent();> and the child div I am talking about is <div class="dropdown-content">. I want to use Vanilla Javascript (preferred) or CSS (not preferred).
TLDR: How do I target only current hovered element from HTML/CSS class in Vanilla Javascript?
How do I do that?
I got this far:
HTML
<!--Lab 1-->
<!--Each individual box.-->
<div class="box">
<!--The box inside each individual box. Think of it as like bubble wrap inside a box.-->
<div class="inside-box" onMouseOver="showDDContent();" onMouseOut="hideDDContent();">
<!--The div with an image in it. Top one inside the box div.-->
<div>
<a href="Lab_01/LB1_WeiJianZhen_DD.html">
<!--Get an image with 300px width by 200px height. Make it responsive.-->
<img src="../../../Visual Content/placeholder.jpg" alt="Under Contruction" class="imgGrids">
</a>
</div>
<!--The div that contains the heading or title of the lab.-->
<div class="txtBar">
<h3>Lab 1</h3>
</div>
<!--The div that drops down to explain the lab with some text.-->
<div class="dropdown-content">
<p>My first website ever made in an HTML file! Describes a bit about the process of making a very basic website like mine.</p>
</div>
<!--End of inside box div.-->
</div>
<!--End of box div.-->
</div>
CSS
/*Creates the styling of the dropdown box.*/
.dropdown-content {
display: none;
position: relative;
background-color: #62ff36;
box-shadow: 0px 8px 16px 0px rgba(56, 255, 42, 0.8);
padding: 12px 0px;
z-index: 1;
}
JavaScript
function showDDContent() {
document.getElementsByClassName("dropdown-content").style.display = "block";
}
function hideDDContent() {
document.getElementsByClassName("dropdown-content").style.display = "none";
}
The easiest, most performant and overall definitely best way to solve this problem clearly is using CSS.
.inside-box:hover .dropdown-content { display: block; }
If for whatever reason you insist go with Javascript (which I do explicitly not recommend), you are going to have to add 2 listeners to each .inside-box, one for mouseenter, the other for mouseleave:
document.querySelectorAll('.inside-box').forEach(insideBox => {
insideBox.addEventListener('mouseenter', () => insideBox.querySelector('.dropdown-content').style.display = 'block');
insideBox.addEventListener('mouseleave', () => insideBox.querySelector('.dropdown-content').style.display = 'none');
})
Using inline event listeners like you suggested is considered very bad practice, so don't try that.

How do I toggle view/display of custom HTML elements?

thank you for taking the time to review my question! :-) I am attempting to write better, cleaner, more maintainable HTML using custom HTML elements as opposed to the traditional 'div' methods. I have a very simple example that works using a div and a class on it to map my link to the div that I want to show/hide and this does work. I include this as a working example of the kind of functionality I am trying to produce:
<html>
<head>
<style>
<!-- Not sure if display or visibility is the way to go so will look -->
<!-- that later, for now just setting both as that works -->
<!-- For some reason doing this does not seem to work -->
.hidden {
display: none;
visibility: hidden;
}
.unhidden {
display: block;
visibility: visible;
}
<!-- but, doing this does, anyone any idea why? -->
.hidden { display: none; }
.hidden { visibility: hidden; }
.unhidden { display: block; }
.unhidden { visibility: visible; }
</style>
<script type="text/javascript">
function toggle_view_div(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='hidden')?'unhidden':'hidden';
}
}
</script>
</head>
<body>
<p>
This test shows or hides a div referenced by its class
</p>
Do the test
<div id="testToggleDivID" class="hidden">
<h3>Testing Toggling HTML</h3>
</div>
</body>
</html>
However, I am trying to provide this kind of functionality with multiple links to multiple sets/subsets of text, I have tried the following but am obviously doing something silly as I can't get it to work:
<html>
<head>
<script type="text/javascript">
function toggle_view_node(nodeID) {
nodeID.getAttribute('visibility')=('hidden')?item.setAttribute('visibility','visible'):item.setAttribute('visibility','hidden');
nodeID.getAttribute('display')=('none')?item.setAttribute('display','block'):item.setAttribute('display','none');
}
</script>
</head>
<body>
<p>
This test shows or hides Topic 1 custom element, (or at least attempts to
</p>
Topic 1
<p>
This test shows or hides Topic 2 custom element, (or at least attempts to
</p>
Topic 2
<p>
<p>
This test shows or hides the Intro custom element, (or at least attempts to
</p>
Introduction
<p>
This test shows or hides the Detail custom element, (or at least attempts to
</p>
Detail
<p>
<Intro>Some introduction text giving a more detailed overview that may want to be hidden by default, but able to be toggled into view with an always visible link such as at the top or on the side of the page</Intro>
<Detail>I may want to add detail with this ability both like this at the root of the document, but potentially inline with other text in custom elements as shown below</Detail>
</p>
<Topic1>
<h1>Topic 1</h1>
<p>
Some topics to be just simple nodes of text.
</p>
</Topic1>
<Topic2>
<h1>Topic 2</h1>
<p>
Other topics to be more detailed topics, <Topic1>potentially including aspects of that can share the toggle feature for the root level topic 1, as per all topic 1 nodes</Topic1> though generally referencing only topic 2 content. <Detail>However it would be nice to be able to toggle not directly relevant, but nice to have detail as well</Detail>
</p>
</Topic2>
<Topic3>
<h1>Topic 3</h1>
<p>
<Intro>Some topics might want an intro<Detail>, that may want further detail contained in them</Detail> that would also provide sufficient intro in itself.</Intro>
So, is this possible? I don't want specific control of sub custom elements, and can do it with div's and assigned classes if I really have to, but surly it is possible with a bit of special JS or CSS to do what I am looking for?</p>
</Topic3>
</body>
</html>
Please, can someone help me figure out what I am doing wrong. I really want to produce the aforementioned functionality with a simple bit of CSS or JS that is as dynamic as possible. Ideally I wont need to specify specific (especially repeated code for each topic or HTML tag that I want the ability to show/hide via a button/link. Obviously, I will probably have to set a few default assignments, maybe turning detail off by default, but if I can avoid required extra repetitive code for each "context" I wish to flip that would be amazing!!!
Any pointers in any direction that can help me achieve what I am attempting without having to use jQuery or a verbose library over and above JS and CSS would really make my day!
Many thanks in advance and apologies if I am doing something really stupid, I haven't done that much work with custom elements and so probably am.
Kind regards,
James
** Latest Attempt **
<html>
<head>
<style>
<!-- Not sure if display or visibility is the way to go so will look -->
<!-- that later, for now just setting both as that works -->
<!-- For some reason doing this does not seem to work -->
.hidden {
display: none;
visibility: hidden;
}
.unhidden {
display: block;
visibility: visible;
}
<!-- but, doing this does, anyone any idea why? -->
.hidden { display: none; }
.hidden { visibility: hidden; }
.unhidden { display: inline; }
.unhidden { visibility: visible; }
<!-- Playing with something like this, ideally I would -->
<!-- configure the show/hide state of my custom HTML tags -->
<!-- universally in a similar way? -->
Topic1.hide { display: none; }
Topic2.hide { display: none; }
Topic3.hide { display: none; }
Intro.hide { display: none; }
Detail.hide { display: none; }
<!-- Another attempt to configure switch state but does not work either -->
Topic1 { className: unhidden; }
Topic2 { className: unhidden; }
Topic3 { className: unhidden; }
Intro { className: unhidden; }
Detail { className: unhidden; }
</style>
<script type="text/javascript">
// This works, but is not clean
function toggle_view_div(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='hidden')?'unhidden':'hidden';
}
}
// I am now attempting to use this on 'Topic1' as per the suggestion
// in the comments of this post, for some reason it does not work, wondering if
// I need to do a .forEach to parse the set of nodeID's of the 'Topic1' in this
// example, but if working whatever HTML tag name that I want to toggle in or
// out of view
function toggle_view_node_id(nodeID) {
var item = document.getElementById(nodeID);
if (item) {
item.className=(item.className=='hidden')?'unhidden':'hidden';
}
}
// This does not work but I have left to show what I tried that did not work
function toggle_view_node(nodeID) {
if (nodeID) {
nodeID.getAttribute('visibility')=('hidden')?item.setAttribute('visibility','visible'):item.setAttribute('visibility','hidden');
nodeID.getAttribute('display')=('none')?item.setAttribute('display','block'):item.setAttribute('display','none');
}
}
</script>
</head>
<body>
<p>
This test shows or hides a div referenced by its class
</p>
Do the test that works using extra layer of div with mapped class
<p>
This test shows or hides Topic 1 custom element,
(or at least attempts using the suggestion in this post
comments to try to make work without inline JS and call a
function to do it as with my working example, unfortunatly
however, this still does not seem to work :(
</p>
Topic 1
<p>
This test shows or hides Topic 2 custom element,
(or at least attempts to using existing method that doesn't work
</p>
Topic 2
<p>When I have it working I hope to be able to have: </p>Topic 3
<p>And... </p>Intro
<p>And this... </p>Detail
<div id="testToggleDivID" class="hidden">
<h3>Testing Toggling HTML into view using a div and associated class of hidden, can I not do this on a custom element?</h3>
</div>
<p>
<Intro>Some introduction text giving a more detailed overview that may want to be hidden by default, but able to be toggled into view with an always visible link such as at the top or on the side of the page</Intro>
<Detail>I may want to add detail with this ability both like this at the root of the document, but potentially inline with other text in custom elements as shown below</Detail>
</p>
<Topic1>
<h1>Topic 1</h1>
<p>
Some topics to be just simple nodes of text.
</p>
</Topic1>
<Topic2>
<h1>Topic 2</h1>
<p>
Other topics to be more detailed topics, <Topic1>potentially including aspects of that can share the toggle feature for the root level topic 1, as per all topic 1 nodes</Topic1> generally referencing only topic 2 content. <Detail>However it would be nice to be able to toggle not directly relevant, but nice to have detail as well</Detail>
</p>
</Topic2>
<Topic3>
<h1>Topic 3</h1>
<p>
<Intro>Some topics might want an intro<Detail>, that may want further detail contained in them</Detail> that would also provide sufficient intro without.</Intro>
So, is this possible? I don't want specific control of sub custom elements, and can do it with div's and assigned classes if I really have to, but surly it is possible with a bit of special JS or CSS to do what I am looking for?</p>
</Topic3>
</body>
</html>
you don't need a .unhidden class, only a .hidden class. It looks like:
.hidden{
display:none;
}
simply use classList like classList.toggle("hidden") or .add or .remove.

Force hover state secondary element on click

quick question from a complete JS noobie.
On a site, I have an image of a product consisting of basically two parts, then I have a row of small .png thumbnails .colorthumbnail of those separate parts with transparent backgrounds. In the CSS I set it so that when hovering the thumbnails, it enables the .colorzoom class that overlays a big version of the same color option over the original product picture using position: absolute.
HTML:
<div class="coloroptions">
<div class="j210desertsand">
<div class="colorthumbnail">
<a href="javascript:void(0)" id="colorpicker">
<img src="img/products/colors/j210desertsand.png"></a>
<span class="colorzoom"><img src="img/products/colors/j210desertsand.png">
</span></div></div>
<div class="j210platinum">
<div class="colorthumbnail">
<a href="javascript:void(0)" id="colorpicker">
<img src="img/products/colors/j210platinum.png"></a>
<span class="colorzoom"><img src="img/products/colors/j210platinum.png">
</span></div></div>
</div>
The <div class="j210desertsand">classes are simply there so I can easily hide a single color option using CSS and the next colour will line up. The anchor points are there cause after some research I found I should actually make the thumbnails clickable and with a href="javascript:void(0)" they don't actually link anywhere or reload the page.
CSS: (Excuse the mess, I'm inexperienced)
.coloroptions {
width: 60%;
margin-left: 40%;
}
.colorthumbnail {
margin-left: -45%;
}
.colorthumbnail img {
float: left;
max-width: 16%;
padding-right: 5px;
position: relative;
}
.colorthumbnail .colorzoom {
position: absolute;
width: 253%;
margin-top: 6.9%;
display: none;
margin-left: -3.6%;
}
.colorthumbnail:hover .colorzoom {
display: block;
}
Now this appears to work fine, but because there are two different parts I want to give the user the ability to combine color options and obviously you can't hover over two images at once. After some more research I found that I need Javascript to force the :hover state on click. But I'm gonna be honest, I have no idea what I'm doing. This is what I have:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<!-- -----------------------JSQuery------------------------- -->
<script>
$("#colorpicker").click(function() {
$('.colorthumbnail:hover').toggleClass('colorthumbnail:hover .colorzoom');
});
</script>
<!------------------------ JSQuery End -------------------------->
However this does not appear to be working. Did I get the linked script in the <head> right? It did work alright with the 'Hello World' pop-up test. Did I get the classes in the script right? I'm a little stuck and help would be appreciated! Much love for the community.
Try adding your code like this:
$( document ).ready(function() {
$("#colorpicker").click(function() {
$('.colorthumbnail:hover')
.toggleClass('colorthumbnail:hover.colorzoom');
});
});
When trying to use jquery you need to make sure the page is loaded so it can perform dom manipulation.
source: https://api.jquery.com/ready/
Here is a jsFiddle demo: https://jsfiddle.net/Lv571n1w/
If you inspect element you can see it toggle the classes when clicked.

JavaScript - tooltip div on hover

I'd like to implement this situation: user hovers link and on his screen appears div with additional information.
There is no problem, to generate div with absolute position, populate data and display it with jQuery, but the problem is with maintainability. I want to separate logic and view. What if I'd like to change page layout in the future? How programmer will know, that some part of page exist in JavaScript file?
Is it some elegant way to separate view (in my case HTML structure) and logic (data obtained from server in JSON using JS script) and combine them? Is it any ... templating engine or something like that in JavaScript?
You can generate your HTML entries like this
<a>
My Cool Link
<div class="tooltip">
This link is awesome!
</div>
</a>
And use CSS to style the tooltip:
(The important part is a:hover .tooltip and everything except background on .tooltip
a {
display: inline-block;
}
a:hover .tooltip {
visibility: visible;
}
.tooltip {
position: relative;
top: 20px;
left: -50%;
display: inline;
visibility: hidden;
background: #eee;
}
Example: http://jsfiddle.net/4K7sB/
Then you just need to populate the elements with the correct text using JS.
Bootstrap does all this and more: http://getbootstrap.com/javascript/#tooltips
To put it in:
$('#example').tooltip(options)
And the markup being:
<div class="tooltip">
<div class="tooltip-inner">
Tooltip text here!
</div>
<div class="tooltip-arrow"></div>
</div>
Go to the link for a more detailed explanation on how to implement it
You can alter the Title="information" dynamicaly by some program or script and use the following code to display it as a tool tip,found it on net
http://www.webdesignerdepot.com/2012/11/how-to-create-a-simple-css3-tooltip/
Just add title attribute in div tag like below code....
<div title="First Div">StackOverFlow StackOverFlow StackOverFlow
StackOverFlow StackOverFlow StackOverFlow StackOverFlow StackOverFlow
StackOverFlow </div>
</div>
<br /><br />
<div title="Second Div">StackOverFlow StackOverFlow StackOverFlow
StackOverFlow StackOverFlow StackOverFlow StackOverFlow StackOverFlow
StackOverFlow </div>
</div>
just copy paste and check.

Categories

Resources