Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add class on html element when it gets visible on screen

I want to add class to the element when it gets visible on screen when scrolling:

<button class='btn btn-default' >
   Hello
</button>

I want to add class to 'btn-default' when the button gets visible on screen after scrolling or when page reloads.

like image 547
Ilyas karim Avatar asked Dec 14 '15 06:12

Ilyas karim


People also ask

Can you add class to HTML element?

HTML elements can have an id and/or class attribute. The id attribute assigns a name to the element it is applied to, and for valid markup, there can be only one element with that name. The class attribute assigns a class name to the element, and that name can be used on many elements within the page.

How do you make an element always visible in CSS?

You need to set the position of the div to Fixed in CSS. See this link for more information. You will need to set position using the top and left in css as well so it knows where to fix it!

Is element visible on screen?

When an element is in the viewport, it appears in the visible part of the screen. If the element is in the viewport, the function returns true . Otherwise, it returns false .

How do I add a class to a CSS element?

If you want to use a class, use a full stop (.) followed by the class name in a style block. Next, use a bracket called a declaration block that contains the property to stylize the element, such as text color or text size. CSS Classes will help you stylize HTML elements quickly.


1 Answers

Try visible selector as in :

$(window).on('scroll', function(){
    if ($(".btn").is(':visible')){
        $(".btn").addClass("btn-default");
    }
});
like image 142
Kurenai Kunai Avatar answered Sep 24 '22 13:09

Kurenai Kunai