JavaScript – How to Add CSS Class on Scroll

cssjavascriptscript

how to add class into div using on scroll in magento.

i have javascript like this

var $j = jQuery.noConflict();
$j(window).scroll(function() {    
    var scroll = $j(window).scrollTop();

    if (scroll >= 100) {
        $j(".page-header").addClass("header-bar");
    } else {
        $j(".page-header").removeClass("header-bar");
    }
});

that javascript will add or remove header-bar class from div with page-header class in it.
it look like this
<header id="header" class="page-header">
will become <header id="header" class="page-header header-bar">if i scroll down the page.

I tried using single html file, it is working perfectly, but then when i apply it in magento, it is not working, but no error message displayed.

The way i apply it into magento is like this:

First, i put that javascript into one file named header-effect.js and i store the file in skin\frontend\rwd\default\jsfolder.
After that, i add header-effect.js in page.xml <action method="addItem"><type>skin_js</type><name>js/header_effect.js</name></action>

I clear magento cache, refresh the page, scroll down the page but nothing is happen, i check page source and header-effect.js is loaded.

Am i doing it correctly?

Best Answer

For common Jquery errors, check if following steps are carried out:

  1. Have you checked the console of your browser for any errors that might have occured.

  2. Magento does not include jquery by default. Have you included it?

  3. Magento requires jquery.noconflict script to be added at the end of the jquery scripts. This stops the conflict between jquery and magento's default prototype.

  4. After including jquery.noconflict, I recommend not using the "$" sign for accessing jquery variables. Try using jQuery instead of $ everywhere.