TheAnswer42
TheAnswer42

Reputation: 21

trigger a CSS :hover with javascript by scrolling

I am working on a Website with fixed menu at the top of the Site. If you hover over the navigationbar it moves down to reveal the links. The hover is realised with css classes.

The navigation should be shown completely, when you enter the site or scroll to the top.

I am trying to realise it using a javascript method which uses with the scroll progress.

$(window).scroll(function() {
	var wS = $(this).scrollTop();
	if (wS > 200){         
		alert('you have scrolled to the h1!');
                $document.getElementById('awning').addClass('awning:hover');
   	        $document.getElementById('nav').addClass('awning:hover #nav');
     }
});

Does it make sense or is there a better way to do it?

The alert doesn't even show up

Upvotes: 1

Views: 661

Answers (2)

Ala Eddine JEBALI
Ala Eddine JEBALI

Reputation: 7821

Please use the code below and click on the 2nd value (200)

$('.wi').on( "click", function() {
    console.log('clicked');
    var temp = $('.wi');
    if (temp.hasClass('wi-celsius')) {
        alert("Current is 'Celsius'... updating it to 'Fahrenheit!'");
        var convertedTemp = parseInt(temp.text()) * 9 / 5 + 32;
		temp.text(convertedTemp);
		temp.removeClass('wi-celsius');
		temp.addClass('wi-fahrenheit');
    }else  {
        alert("Current is 'Fahrenheit'... updating it to 'Celsius!'");
        var convertedTemp = (parseInt(temp.text()) -32)/ (9/5);
		temp.text(convertedTemp);
		temp.removeClass('wi-fahrenheit');
		temp.addClass('wi-celsius');
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<ul id="list">
    <li>100</li>
    <li>&nbsp;<i class="wi wi-celsius">200</i></li>
    <li>300</li>
 </ul>

Is that what you need?

Upvotes: 0

Krzysztof Atłasik
Krzysztof Atłasik

Reputation: 22595

You cannot assign pseudo-classes like this. A pseudo-class is used to define a style of element when special state occurs (for example hovering over element, link being already visited) or element is somehow special( first of kind, even etc.).

You will have to create additional class in css like this:

#awning.revealed{ /* notice there is no space between selectors */
    /*your css code goes here (same as in :hover)*/
}

And then just add class to element like this:

 $document.getElementById('awning').addClass('revealed');

Upvotes: 1

Related Questions