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.

4
  • 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: stackoverflow.com/a/17244507/519413 Commented Jun 19, 2018 at 7: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 Commented Jun 19, 2018 at 7:55
  • Toggling a class is the simplest workaround. Is there a specific reason you cannot just do that? Commented Jun 19, 2018 at 7: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 Commented Jun 19, 2018 at 8:01

2 Answers 2

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>

Sign up to request clarification or add additional context in comments.

4 Comments

In the question: I need a solution without adding a new css class.
@RoryMcCrossan corrected.
True. I suppose in the loosest sense it works, but I think the OP is more asking 'how can I trigger the CSS :hover selector from JS'.
Yeap. I need to trigger :hover but not handle. But still, thank you for try.
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>

5 Comments

Thank but it is not what I need. Check this comment stackoverflow.com/questions/50923177/…
@DmytroHuz, you can't do it.
yeap already saw in duplicate topic. So trying to find another solution now.
@DmytroHuz,good luck.
Thank you, man! =)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.