1

I have 5 squares. Hovering a square makes it green. Lets say I want to hover last-child and apply the blue to first-child, nth-child(1), nth-child(2), nth-child(3) is that possible without involving Jquery?

Same logic as would I hover square 3, then i'd want square 1+2 to become green.

Fiddle

user1231561
  • 3,239
  • 6
  • 36
  • 55
  • no it's not possible - you need JS – Johannes Jun 25 '17 at 22:56
  • You should tag your question Javascript, not jQuery. If you tag it jQuery then it means you want an answer related to jQuery. – Clonkex Jun 25 '17 at 22:57
  • 3
    like this? https://jsfiddle.net/0q8om77w/4/ – Michael Coker Jun 25 '17 at 22:58
  • Clonkex - in case it would need Javascript, I tagged it with Jquery, because i'd be looking for a Jquery answer then! – user1231561 Jun 25 '17 at 23:00
  • Michael Coker > Yes exactly!! :) Didn't know that infinite sign! Is it standard CSS3 aka. cross-browser reliable? – user1231561 Jun 25 '17 at 23:02
  • I guess it's not possible to get working in correct left to right direction with normal floats? – user1231561 Jun 25 '17 at 23:09
  • That's not the infinite sign, that's called a `tilde` (pronounced TILL-duh). And yes it's standard and cross-browser compatible :) [Reference](https://www.w3.org/TR/selectors/#general-sibling-combinators) and [caniuse](http://caniuse.com/#feat=css-sel3) – Clonkex Jun 25 '17 at 23:18

1 Answers1

0

As mentioned already, without Javascript it won't be really possible. Maybe with CSS 4?

Here is a quick version with plain javascript (no jQuery)
live demo

// Get all block-items
const items = document.querySelectorAll( '.block-item' );

// Helper function to set active class
const setState = ( index, active ) => {
  if ( index >= 0 && items[ index ] ) {
    // Only add active class when argument active is true
    // Otherwise remove it
    items[ index ].classList.toggle( 'active', active );
  }
}

const onMouseEnter = index => {
  setState( index - 1, true );
  setState( index - 2, true );
};
const onMouseLeave = index => {
  setState( index - 1, false );
  setState( index - 2, false );
};

// Iterate over all items and add event listener
items.forEach( ( item, index ) => {
  item.addEventListener( 'mouseenter', () => onMouseEnter( index ) );
  item.addEventListener( 'mouseleave', () => onMouseLeave( index ) );
} );
lumio
  • 7,428
  • 4
  • 40
  • 56