How to link to a collapsed hidden tabindex element with # - html

I am working on a glossary and have made a bulky file with terms in columns behind which are hidden texts (with display:none), in plain css/html.
Each entry looks like this in code: <div class=w tabindex=0>Achidrupa<div class=tt>Here follows hidden explanation.</div></div>
Instead of :hover I use :focus so the explanation is kept opened up in a sort of popup window, without use of Java or JS.
As there are entries with slightly different spelling I like to refer to the main entry, but not with the rather clumsy ‘‘See entry blah blah blah’’.
So, I like to make internal links, as we are used to with # and name or id in the linked-to element. But whatever I try, I cannot get another entry opened from the opened window with the link. Can I get some help with that? Very grateful for any solution.
I believe I did not make this issue clear enough from the start. I have the following code, including tabindex=0 and with .w:focus .tt{display: inline-block ; cursor:pointer; } in css.
<div class=w tabindex=0 name="alpha">1ste Entry Alpha <div class=tt>
Follows text as explanation on alpha which becomes visible after a click on Entry Alpha, otherwise it stays hidden with css display:none. [Probably about or 100 words here.]</div></div>
<div class=w tabindex=0 name="beta"> 2nd Entry on beta <div class=tt>
Follows text as explanation on beta which <a href=#alpha>link to entry alpha </a> after a click. [Probably about or 100 words here.]</div></div>
What I need is the possibility to open window 1st Entry Alpha when I click in opened window Entry on beta and click on ‘link to entry alpha’.
I am sorry but the delivered javascript code and snippet didn’t work. It would not open any focused element. By the way, the glossary works great in this way, except for the internal linking.

Here is a solution using javascript: get the hash, find element with corresponding name and focus it. The whole thing is wrapped in onload otherwise the browser wont focus the element.
window.onload = function () {
var hash = window.location.hash.substr(1);
if (hash) {
var target = document.getElementsByName(hash)[0].focus()
}
}
.w {
display: block;
color: black;
text-decoration: none;
}
.w > div {
display: none;
}
.w:focus {
outline: none;
}
.w:focus > div {
display: block;
}
<a name="q1" href="#q1" class="w">
Question ?
<div>mopm adsma pomfdsapoi mfadsp fasdm pasofdm pasdofi mdfs apfd smapfdso amfp ad</div>
</div>
<a name="q2" href="#q2" class="w">
Question ?
<div>mopm adsma pomfdsapoi mfadsp fasdm pasofdm pasdofi mdfs apfd smapfdso amfp ad</div>
</div>
<a name="q3" href="#q3" class="w">
Question ?
<div>mopm adsma pomfdsapoi mfadsp fasdm pasofdm pasdofi mdfs apfd smapfdso amfp ad</div>
</div>

Related

HTML Validation: Why is it not valid to put an interactive element inside an interactive element?

Disclaimer: I understand that it is not valid HTML. I am trying to understand why is it not allowed?
W3C suggests that an interactive element like button or a mustn't contain another interactive element.
I could find a lot of resources mentioning this rule and some workarounds, also some resources related to how this impacts accessibility and screenreaders, but almost all of those resources talk about the fact that this is a requirement but do not explain why.
https://adrianroselli.com/2016/12/be-wary-of-nesting-roles.html
https://codepen.io/vloux/pen/wXGyOv
Nesting <a> inside <button> doesn't work in Firefox
https://github.com/dequelabs/axe-core/issues/601
I wasn't really able to find an explanation for why is it not allowed? does it lead to any usability problems?
This is a related question:
Why should interactive element not be used within an anchor?
The accepted answer is satisfactory but is not enough to make this rule a requirement. The described situation can be avoided using proper event handling.
Also, if nested interactive content is invalid, how are we supposed to have something like this:
A card which is clickable as a whole, and also has a clickable secondary CTA inside it.
I know a workaround would be to have a primary and secondary CTA inside the card, but shouldn't the above be allowed as well?
Here is a fiddle:
https://jsfiddle.net/t9qbwas5/2/
<button type="button" class="card">
The card itself is the primary CTA.
<br/>
<br/>
some important content to read through.
some important content to read through.
some important content to read through.
<div class="cta">
Secondary CTA
</div>
</button>
.cta {
padding: 4px;
background: #00a9a9;
color: white;
width: 80px;
margin: auto;
margin-top: 8px;
margin-bottom: 8px;
}
.card {
width: 200px;
display: flex;
flex-direction: column;
justify-content: center;
text-align: center;
}
In the above example, I am achieving this by using a clickable div inside the button, but that is not semantic (?) and also functionality wise, it is an interactive element inside another one. I am trying to understand that even if I use this workaround, is it fundamentally wrong to have nested interactive elements? is it a bad design/usability practice?
The answer is actually quite simple in principle. When you click on the interactive element inside another interactive element which function should you trigger?
In your example if I click on Secondary CTA should it fire the function for secondary CTA or should it fire the function for the card?
The fiddle below should demonstrate the problem, tab into the first button and press enter, then tab into the CTA and press Enter.
Obviously you could work around this but I think it demonstates the point.
$('.card').on('click', function(){
console.log("card");
});
$('.cta').on('click', function(){
console.log("cta");
});
.cta {
padding: 4px;
background: #00a9a9;
color: white;
width: 80px;
margin: auto;
margin-top: 8px;
margin-bottom: 8px;
}
.card {
width: 200px;
display: flex;
flex-direction: column;
justify-content: center;
text-align: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" class="card">
The card itself is the primary CTA.
<br/>
<br/>
some important content to read through.
some important content to read through.
some important content to read through.
<div class="cta" tabindex="0">
Secondary CTA
</div>
</button>
This principle then continues through to Screen Readers and other Augmentative and alternative communication (AAC) devices.
Should they take into account the parent element when describing the child element? Should they allow the use of Space to activate if you nest a checkbox within a <button>, should Enter then affect only the button or both?
A card which is clickable as a whole, and also has a clickable secondary CTA inside it.
Although visually imaginable and technically possible, it's not accessible for assistive technologies, like screenreaders
Let's make a simple example:
<button>
Click for action 1
<button>Click for action 2</button>
</button>
The accessible name for the first <button> would be "Click for action1 Click for action 2". And if you define an aria-label="Click for action 1", then the inner button element would not be read at all.
If you really want to make a whole element clickable, you can perfectly use javascript and still be accessible
<div class="outer">
<button type="button" class="card">
The card itself is the primary CTA.
</button>
<br/>
<br/>
some important content to read through.
some important content to read through.
some important content to read through.
<button class="cta">
Secondary CTA
</button>
</div>
<script>
$(".outer").on("click", function() {$(".card").click()});
</script>
<style>
.outer {cursor: pointer}
</style>
With this example, you will correctly have two buttons rendered to screenreaders, the first one "The card itselfis the primary CTA" and the second one "Secondary CTA", while a mouse click on the whole card would lead the same action as the first button.
It's hard to answer "why" questions, because there are many factors to be considered and ultimately the reason is that the specification specifies it, but I'll give it a try.
When this behavior was spec'ed, this design style was not very common. A link was normally either a single image or a small portion of text. Take a look at this link to an article from the year 2000:
]
Only the title and the image are interactive. The rest is simple text.
Even today, this is not so common. Take also look at the Microsoft 365 pricing page:
Note how the card itself is not interactive, only the things inside it. You can see the primary CTA "Buy now" in the form of a button and the secondary CTAs in the form of hyperlinks.
Now, about your example: Is that card really a button? It might be subjective, but for me that's not a button. A button normally appears with a color scheme contrasting with the surrounding page. I would make the card a <div> and the secondary CTA a <button>.
However it might be confusing to users, as the card doesn't seem much interactive to me. Consider adding cursor: pointer to the <div> (beyond all the things necessary for accessibility)`.
I noted you tagged accessibility. I think this is not a great idea for people using screen readers, and I think most screen readers would have problems interpreting a button inside a button (if the browser accepted that at all).
I would use the "Microsoft 365 pricing page approach" instead. It's simpler and works well with HTML.
One important problem is related to event-capturing; if you click on a interactive element nested inside another interactive element(e.g. a select inside a clickable button) there would be an interference here and two case might happen depends on the browser;
case 1 is that both element will raise that event (e.g. click) event
 
case 2 is that parent element will capture the event and the nested element won't raise that event
in fact both cases will result in non-deterministic behavior;
This is not limited to click events actually, but click event is more tangible; Also the screen reader will fail to parse the markup; keyboard-interaction won't work as expected; try it in the snippet below:
del.addEventListener('click', function(){
console.log('deleting ...')
})
save.addEventListener('click', function(){
console.log('saving ...')
})
sel.addEventListener('change', function(){
console.log('changing to', sel.value)
})
<div id='del'>
delete
<button id='save'> save
<select id='sel'>
<option>foo</option>
<option>bar</option>
<select>
<input name='a' type='radio' />
<input name='a' type='radio' />
<input name='a' type='radio' />
</button>
</div>

Add hyperlink IN the hover text

So, I have an image and when hovered on it, some text appears. What I want to do is to add a hyperlink in that text.
For example: Text says "hello my name is" then i want to include "click to find out" as a hyperlink linking to another page in my web application.
I have already tried the below:
<span>hello my name is <a href:"abc.php">click to find out</a></span>
The above is replacing the entire <span>by just showing "click to find out" as a hyperlink.
Any suggestions please ??
code tried:
<span class="text-img">
Diversity index is measured on a scale of 0 to 100.
Higher number indicates a greater degree of relative diversity.<a target="_blank" href="PanelHow.php">test</a>
</span>
Since you have not shared the actual code, it is difficult to find out the exact problem. So i have developed the small example for you. Check the below code and it is working fine.
.test {
display:none;
}
.maindiv {
display:inline-block;
}
.maindiv:hover .test {
display:block;
}
<div class="maindiv">
<img src="http://miumosa.com/assets/products/sample-_20170209104115.png" width="100" />
<span class="test">hello my name is click to find out</span>
</div>

tabindex -1 not working for child elements

I have a div tag with some content getting loaded inside it. The content inside can have buttons, anchor elements, etc. which are focusable. I do not have control over the content but I can modify the 'div' tag attributes.
My problem is the focus still goes to the content (anchor, buttons, etc.) even if I specify the tabIndex -1 to the div tag.
<!-- HTML content here -->
<div tabindex="-1" id="externalContent">
<div>
...
<button>click me</button> <!-- Focus shouldn't come here -->
</div>
</div>
<!-- HTML content here -->
Is there a way to skip the entire content while tabbing ? It's certainly not working with the above code.
Not sure why nobody has mentioned visibility: hidden yet. Setting display: none can in some cases mess up logic when dealing with dimensions of non-visual elements. visibility will persist the dimensions just like opacity: 0 would do, but also disable any tabbable children.
Example:
<div style="visibility: hidden;">
I'm only tabbable if my parent is visible!
</div>
It is possible leave an element BOTH visible and unfocusable, together with its children.
It's done via the HTML property inert: https://html.spec.whatwg.org/multipage/interaction.html#inert.
It's not widely supported yet, but there is a polyfill: https://github.com/WICG/inert.
npm install --save wicg-inert
require('wicg-inert')
<section inert>
I am visible, but not focusable!
</section>
Setting tabindex="-1" allows you to set an element’s focus with script, but does not put it in the tab order of the page. It also does not pull the children of something out of keyboard tab order.
tabindex="-1" is handy when you need to move focus to something you have updated via script or outside of user action.
If you are trying to remove an element from tabindex altogether, whether for screen readers or keyboard users, you will likely have to choose between one of these:
Hide it altogether (via display: none),
Use script on the element so that when it receives focus, the script shifts the focus somewhere else.
Without context (a working URL, a reason that you want to do this), this sounds very much like the opposite of accessibility. I encourage you not to mess with focus unless you have a very good reason.
The nearest you can go is using an iframe element, injecting your HTML inside using javascript.
first link
<iframe id="iframeid" tabindex="-1"></iframe>
second link
<script>
document.getElementById('iframeid').contentWindow.document.body.innerHTML="<button>click me</button>";
</script>
But, this will lead to accessibility problems, like announcing links or buttons which can't be accessed by your keyboard.
[tab-index="-1"] > * {
visibility: hidden;
}
This hides any interactive children from tab navigation or mouse clicks, but leaves the parent in the shadow DOM and leaves all sizes of parent and children.
For making tabindex -1 for child elements, lets say you have a wrapper div,
// answer with respect to react, when we don't want grid filter to be accessible if its collapsed
//this answer is for a special case - where we dont have refs and tabIndex Props does matter for big nested elements
// Render method
// if Input and Button are from some kind(eg material UI) of Libraries which dont get tabIndex as a prop and doesnt give refs.
render() {
return (
<div id="wrapper" tabIndex={isCollapsed ? -1 : 0 } >
<div>
<Input />
</div>
<div>
<Button />
</div>
</div>
)
}
componentDidMount() {
this.changeTabIndex()
}
componentDidUpdate(prevProps, prevState){
if(prevState.isCollapsed !== this.state.isCollapsed) {
this.changeTabIndex();
}
}
changeTabIndex() {
const wrapper = document.getElementById("wrapper");
const buttons = wrapper.getElementsByTagName("button");
const inputs = wrapper.getElementsByTagName("input");
const arr = Array.from(buttons).concat(Array.from(inputs));
arr.foreach((elem) => { elem.setAttribute("tabIndex", this.state.isCollapsed ? -1 : 0 )});
}

Div displaying as a link while hovering over it [duplicate]

Is it possible to wrap an <a> tag around <div>s like so:
<a href=etc etc>
<div class="layout">
<div class="title">
Video Type
<div class="description">Video description</div>
</div>
</div>
</a>
Eclipse is telling me the div's are in the wrong place?
If this is not allowed. How can I make the entire 'layout' class become a link?
That structure would be valid in HTML5 since in HTML5 anchors can wrap almost any element except for other anchors and form controls. Most browsers nowadays have support for this and will parse the code in the question as valid HTML. The answer below was written in 2011, and may be useful if you're supporting legacy browsers (*cough* Internet Explorer *cough*).
Older browsers without HTML5 parsers (like, say, Firefox 3.6) will still get confused over that, and possibly mess up the DOM structure.
Three options for HTML4 - use all inline elements:
<a href=etc etc>
<span class="layout">
<span class="title">
Video Type
<span class="description">Video description</span>
</span>
</span>
</a>
Then style with display: block
Use JavaScript and :hover:
<div class="layout">
<div class="title">
Video Type
<div class="description">Video description</div>
</div>
</div>
And (assuming jQuery)
$('.layout').click(function(){
// Do something
}):
And
.layout:hover {
// Hover effect
}
Or lastly use absolute positioning to place an a anchor with CSS to cover the whole of .layout
<div class="layout">
<div class="title">
Video Type
<div class="description">Video description</div>
</div>
<a class="more_link" href="somewhere">More information</a>
</div>
And CSS:
.layout {
position: relative;
}
.layout .more_link {
position: absolute;
display: block;
top: 0;
bottom: 0;
left: 0;
right: 0;
text-indent: -9999px;
z-index: 1000;
}
This won't work with older versions of IE, of course.
While the <a> tag is not allowed to contain <div> element, it is allowed to contain other inline elements such as <span>.
When I encountered the problem i swapped the div tag with a <span>. Since the span tag is an inline element, you need to apply a display:block to the css of your <span> element, in order to make it behave like the <div> block element.
This should be valid xhtml and does not require any javascript.
Here's an example:
<a href="#">
<span style="display:block">
Some content. Maybe some other span elements, or images.
</span>
</a>
Another simple solution - just add an onclick event handler to the div thusly:
<div class="layout" onclick="location.href='somewhere'">
<div class="title">
Video Type
<div class="description">Video description</div>
</div>
</div>
This works great for me but there is one small gotcha. I'm not sure how search engine friendly this is. I fear that google's web crawlers might not find this link so I also tend to include a traditional A HREF link somewhere in the block like this:
<div class="layout" onclick="location.href='destination_url'">
<div class="title">
Video Type
<div class="description">Video description</div>
</div>
This is a link
</div>
Timothy's solution is correct ... instead of wrapping an anchor around a div ... you simply give layout to the anchor element with display:block and add the size and width of the anchor ...
.div_class { width: 100px; height: 100px; }
.div_class a { width: 100px; height: 100px; display: block; }
<div class='div_class'></div>
HTML provides two general elements, where div is a natural block element, and span is a natural inline element. All other elements are similarly assigned to be a natural block or inline.
Now, while both can be made by css display to be any of inline, inline-block or block, they are still treated for enclosure purposes as their natural selves, hence the warning messages. Leopards and spots sort of thing.
However, css is only meant to be for making what an element looks like (presentation), but not actually be like (functionality), so it doesn't change an element's basic nature, though that gets very fuzzy in practice. A span made block becomes a bully that kicks everything else off the line, which is very un-inline sort of behaviour.
So, to mitigate against possible conflicts between their natural and css-induced behaviours, it is better to allow:
div or any natural block tag to only ever be block or inline-block.
span or any natural inline tag to only ever be inline or inline-block.
This will also mitigate against tending to build page structures that will likely end up churning out error and warning messages.
Basically, NEVER embed a natural block tag inside a natural inline tag, at any depth.
Why there is a really a distinction is perhaps due to a simplistic idea of what HTML was going to be used for when it was first dreamed up.
Certainly, framework makers got around a lot of these what-to-embed-where problems by just using myriads of divs everywhere, and 'divitis' was born, and still alive and well in every framework. Just have to press F12 in a browser on almost any commercial web page and drill down through a dozen divs. This very page has 15 unbroken levels of divs.
It is not hard to see why just settling on divs made sense. For example, a p tag may have a bunch of links to various sites, and that is ok because inline links are allowed in a block p. However, if not wanting to have query variables visible in those urls, then buttons are required. If only one, then the p can be put inside a form, as a p cannot contain a form.
The formaction attribute on a button can be used to target a url other than the form default, but it still does not allow independent forms, each with their own set of hidden inputs. A button can use the form attribute to use it with a form that isn't an ancestor, but it can get messy to keep track of.
For multiple links to different sites to appear as part of one paragraph though, the only way is to use a div instead of the p and then wrap each button in its own form set to inline. Most frameworks have to cope with so much more complex scenarios that nested divs are the only way to go.
It meant that they really only had to manage one tag per purpose and manage it as if it was an isolated environment. So what was meant to be an occasionally-used functional grouping tag became the web's Lego block. And none of them are going to risk breaking their frameworks by converting to HTML5 semantic tags in a hurry. In the end, semantic tags only really work for fairly static content rather than rich interactive sites.
I had tried to create custom solution using jQuery, which would imitate same behavior as a tag does, for parent DIV.
DEMO:
https://jsfiddle.net/kutec/m9vxhcke/
As per W3C standard, you cannot do this:
<div class="boxes">
<a href="http://link1.com" target="_blank">
<div class="box">
<h3>Link with _blank attr</h3>
</div>
</a>
</div>
You must follow this:
<div class="boxes">
<div class="box">
<h3>
Link with _blank attr
</h3>
</div>
</div>
But by following above code, you wouldn't get the whole DIV clickable :).
Correct structure should be something like this, which also allows you to click over the DIV to redirect on the given href value:
<div class="boxes" data-href="http://link1.com" data-target="_blank">
<div class="box">
<h3>
Link with _blank attr
</h3>
</div>
</div>
Simple Solution:
$(function() {
$('.boxes a').each(function(){
var aTag = $(this).attr('href');
$(this).parent().attr('data-href',aTag);
$("[data-href]").click(function() {
window.location.href = $(this).attr("data-href");
return false;
});
})
}(jQuery));
Dynamic Solution:
(function ( $ ) {
$.fn.dataURL = function() {
// variables
var el = $(this);
var aTag = el.find('a');
var aHref;
var aTarget;
// get & set attributes
aTag.each(function() {
var aHref = $(this).attr('href');
$(this).parent().attr('data-href',this);
aTarget = $(this).attr('target');
$(this).parent().attr('data-target',aTarget);
});
// imitation - default attributes' behavior on "data-" attributes
$(el).delegate('[data-href]','click', function() {
var loc = window.location.href;
loc = $(this).attr("data-href");
aTarget = $(this).attr('data-target');
if(aTarget == "_blank"){
window.open(loc);
} else {
window.location = loc;
}
return false;
});
//removing attributes from selector itself
el.removeAttr('data-href');
el.removeAttr('data-target');
// css
$('[data-href]').css('cursor','pointer');
};
}( jQuery ));
Final call:
<script>
$('.boxes').dataURL();
</script>
Hope this would be helpful :)
You would just want to style the "a" tag as display: block;
Eclipse is appropriately telling you that your HTML is not to spec (as a div tag is not allowed in an anchor tag).
But, since you seem to want to be visually making the anchor look like a big-ol-box, then simply style it as such :)
One easy way to make the div a link/clickable is by using html javascript onclick attribute:
<div class="clickable-div" onclick="location.href='#';"><div> ... </div></div>

CSS hover over one paragraph, change background of the previous one

For practice and training CSS im trying to do something like:
In other words, I'm trying something like this: when I hover over third paragraph, second paragraph needs to get color like on picture.
I'm trying with pseudo-classes :hover and :before (or :after) with content attribute set to "", setting background to #E7A51B and opacity to 0.3 but It doesn't work.
HTML need to be like this:
<body>
<div class="app">
<p> First paragraph </p>
<div class="active">
<p> Second paragraph </p>
</div>
<br>
<div>
<p> Third paragraph </p>
</div>
</div>
</body>
EDIT: Thanks everyone on comments. Reading your comments I get idea to ask that is it possible some more generic approach, something like:
If I hover over element with class="foo1" background of element with class="foo2" get changed?
current CSS (Selectors Level 3)
With the current CSS standard, unfortunately what you are trying is not possible. However, what is possible at the moment?
Given the following markup:
<div class="app">
<p> First paragraph </p>
<p> Second paragraph </p>
<p> Third paragraph </p>
</div>
You can target elements that are on the same level (same parent) and follow your initial element you interact with (e.g. :hover). → Demo
/* targeting the direct descending sibling of the 3rd paragraph*/
p:nth-of-type(3):hover + p{
color:red;
}
/* targets the 4th paragraph when hovering the second */
p:nth-of-type(2):hover ~ p:nth-of-type(4){
color:blue;
}
/* targets all paragraphs being siblings of the first paragraph */
p:first-of-type:hover ~ p{
color:green;
}
the future (Selectors Level 4)
Selectors Level 4 will (most likely) bring two exciting new feature which can achieve, what you actually try to do:
1) The - what I would call it - subject indicator - it let's you determine, which element of the compound selector you want to target.
!OL > LI:only-child
would target all ordered lists with only have one list element (looks simple, but is not possible with current css).
2) the reference combinator:
label:hover /for/ input
would target an input element, when the label which is referencing it via it's for attribute is hovered.
At the moment this is not supported by any browser yet, but you see, we can be excited what awaits us in the near future of css;)
The :hover method in CSS will only work if you want to hover over an element and change the color of that specific element, it will not work to change a separate one. In other words, you will need to do some simple JQuery. If you're not familiar with JQuery, don't worry, I'll walk you through the steps you'll need. If you're familiar with Jquery and already have the library, skip to step 3 and I'll provide you with the exact code that will make it work. This looks extremely long and painful but that's just because I'm trying to be as thorough as possible. It is actually very simple
Step 1: If you don't know what JQuery is, it is JavaScript that has been rewritten in an easier (in my opinion) syntax. In order for the JQuery to work however, you will need to download the library (syntax) for free at jquery.com. When you get to the website, click the download tab and then download the compressed, production version of JQuery. When you click that to download it, a page opens up with all the code. Copy it all and paste it into your text editor and save it with a .js extension. ex: jquery-library.js.
Tip: make sure it is in the same folder as all of your other html and css documents that you're using.
Step 2: Link your html with the Jquery library you downloaded like this:
<head>
<script type="text/javascript" src="the name of your jquery library file.js"></script>
</head>
Step 3: Create a new file in your text editor with a .js extension. ex: background-color.js. You will also need to link this with your html page. Go to your html page and in the < head > section right underneath the first < script > tag, type:
<script type="text/javascript" src="the name of your javascript file.js"></script>
Your < head > section in the html should now look like this:
<script src="the name of your jquery library file.js"></script>
<script src="the name of your javascript file.js"></script>
Step 4: You will need to make a few simple changes to your html first. The second and third < p > elements both need classes so that the JQuery can identify them:
<div class="app">
<p> First paragraph </p>
<div class="active">
<p class="second"> Second paragraph </p>
</div>
<br>
<div>
<p class="third"> Third paragraph </p>
</div>
Step 5: Now for the JQuery. It is okay if you don't understand the syntax, just copy and paste this into your .js document:
Tip: I added comments to explain each string as much as possible. Anything on a line after a // is a comment.
$(document).ready(function(){ // <-- this string tells the browser to perform the following action once the page has fully loaded
$(".third").mouseenter(function(){
$(".second").css("background-color", "#9CF"); // change this css color to whatever background color you want
}); // when the mouse enters the class "third", the background color of the class "second"
// changes to #9CF
$(".third").mouseleave(function(){
$(".second").css("background-color", "#FFF"); //change this css color to whatever your default background is
}); // when the mouse leaves the class "third", the background color of the class "second"
// changes back to default
});
I hope this helped. Let me know if something doesn't work, but I tested it in safari and firefox and it is extremely basic JQuery so it should work anywhere. Keep in mind that on a mobile device, you can't hover, so try not to make it an essential part of your website.
Here is my solution
My goal was to create a solution that wouldn't require any work on the HTML of the page. I was also trying to create a solution that would be applicable in various scenarios. To do this, I have to use the .prev() method.
$("div p").on("mouseenter", function () {
$(this).prev().css("background-color", "red");
});
$("div p").on("mouseleave", function () {
$(this).prev().css("background-color", "inherit");
});
here is my new code with some jquery
in your html I added class last
http://jsfiddle.net/K4RFX/1/
$('.last').mouseover(function() {
$('.active p').css('background','#f00');
});
$('.last').mouseout(function() {
$('.active p').css('background','none');
});
<body>
<div class="app">
<p> First paragraf </p>
<div class="active">
<p> Second paragraf </p>
</div>
<br>
<div class="last">
<p> Third paragraf </p>
</div>
</div>
</body>
Unfortunately, the modern CSS doesn't have a selector like 'previous element'. We can only use some combinations of hover effects on parent and children elements, like in this demo:
CSS
.wrapper:hover p:first-child {
background: red;
}
.wrapper p:first-child:hover {
background: none;
}
 
HTML
<div class="wrapper">
<p>The 2nd parapraph</p>
<p>The 3rd parapraph</p>
</div>