Aref.Heydari
Aref.Heydari

Reputation: 57

Change Styles Of Element When Another Element Is Active

can i change the style of class 1 when class 2 is focus or hover? is there any way do this with css?

like here.

<button class='class 1'></button>
<button class='class 2'></button>

Upvotes: 1

Views: 4512

Answers (5)

Mamun
Mamun

Reputation: 68933

You can try with jQuery's .hover().

Please note: class names do not allow space in them.

$('.class2').hover(
  function() {
    $('.class1').css({color:'red'});
  }, function() {
    $('.class1').css({color:'blue'});
  }
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class='class1'>Button 1</button>
<button class='class2'>Button 2</button>

Upvotes: 1

htmldevmate
htmldevmate

Reputation: 46

Try this

html

    <button class='class1'>button1</button>
    <button class='class2'>button2</button>

css

    .class1:hover + .class2,
    .class1:active + .class2,
    .class1:focus + .class2{
          background: blue;
     }

    .class2:hover + .class1,
    .class2:active + .class1,
    .class2:focus + .class1{
          background: green;
     }

Thank you.

Upvotes: 2

Nick Parsons
Nick Parsons

Reputation: 50684

This is possible using only CSS, but it can be a bit finicky.

You could use pseudo-classes focus and hover and select the immediately after element with the class .class1. Since + will target the element immediately after you can use flex and order to move your buttons around so they appear in the correct order:

.class2:hover+.class1 {
  background: lime;
  color: red;
}

.class2:focus+.class1 {
  background: red;
  color: white;
}

.wrapper {
  display: flex;
}

.class1 {
  order: 1;
}

.class2 {
  order: 2;
}
<div class="wrapper">
  <button class='class2'>Button2</button>
  <button class='class1'>Button1</button>
</div>

Upvotes: 1

brk
brk

Reputation: 50291

You can do it using mouseover and mouseout

$('.class').on('mouseover', function(e) {
  $('.class').not($(this)).addClass('hover')

})

$('.class').on('mouseout', function(e) {
  $('.hover').removeClass('hover')

})
.hover {
  background: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class='class 1'>Test</button>
<button class='class 2'>Test 1</button>

Upvotes: 3

ellipsis
ellipsis

Reputation: 12152

Try this. It will change the bg color of button 1 when button 2 is hovered on

$(document).ready(function() {
  $('.class2').hover(function() {
    $('.class1').css('background-color', 'blue')},
    function(){
    $('.class1').css('background-color', '')
    })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class='class1'>Button</button>
<button class='class2'>Button</button>

Upvotes: 1

Related Questions