0
<p class="text">Some text</p>

<style>
.text:hover{
    color:red;
}
</style>

How can I trigger hover event that text becomes red via js or jquery? I need a solution without adding a new css class.

Dmytro Huz
  • 1,514
  • 2
  • 14
  • 22
  • 1
    `I need a solution without adding a new css class.` It's not possible then. You cannot invoke the CSS `:hover` selector from JS. See this specific answer in the duplicate I marked for more details: https://stackoverflow.com/a/17244507/519413 – Rory McCrossan Jun 19 '18 at 07:50
  • Thank you for an answer. Very bad to hear it, but now at least I know that it is impossible and will be looking for other ways – Dmytro Huz Jun 19 '18 at 07:55
  • Toggling a class is the simplest workaround. Is there a specific reason you cannot just do that? – Rory McCrossan Jun 19 '18 at 07:55
  • There are a lot of CSS rules I need to change. Plus I use Foundation and I will need to change sources/or rewrite rules in my file as well and I don't want to do that. Also, I will need to add this new class to all js functions which handle hover. So this approach add a lot of work, but as I see I don't have another way – Dmytro Huz Jun 19 '18 at 08:01

2 Answers2

0

You need to use hover() function of JQuery with syntax hover( handlerIn, handlerOut ) as you cannot manipulate :hover from JQuery.

$('.text').hover(
  function(){
    $(this).css('color', 'red');
  },
  function(){
    $(this).css('color', 'black');
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="text">Some text</p>
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
0

Try This:

$(document).ready(function(){
    $('.text').hover(function(){
        $(this).css('color','red');
    },function(){
        $(this).css('color','initial');
    })
})

$(document).ready(function(){
 $('.text').hover(function(){
  $(this).css('color','red');
 },function(){
  $(this).css('color','initial');
 })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<p class="text">Some text</p>
Ehsan
  • 12,655
  • 3
  • 25
  • 44