简体   繁体   中英

Scroll to anchor in Prestashop (Jquery)

please can you help me with small function - Im not skilled in JS / Jquery. I need scroll to anchor in Prestashop, all codes are function only in index.php, not at another pages (product page, category page ..)..

So I need rule for this function be active only on index.php page ..but code bellow is not function:(

jQuery(function($) {
    var url = window.location.pathname;
    var string = "index.php";
    if(url.indexOf(string) !== -1) {  
       $("a.linkscroll").live('click',function(event){
          event.preventDefault();
          var target_offset = $(this.hash).offset() ? $(this.hash).offset().top : 0;       
          var customoffset = 120;
          $('html, body').animate({scrollTop:target_offset - customoffset}, 2000);
        });
    }   
    else {
       echo "nothing there?"
    }
    }(jQuery));

Please, can you help me? (in menu a links I have class a.linkscroll = a href="index.php#some-anchor", so I can use this = another anchors I dont need to be use) ..scroll function I have used only in main page (index.php), anchors have ID (for example a id="some-anchor").

Thank you for your help!

Helllo Jiri

In Prestashop, you can find page name and its associate controller in <body> id.

You can pass the $pagename from your controller file, by assigning it to smarty variable.

The code to get a pagename is below:

$pagename = Dispatcher::getInstance()->getController();

You can override your classes/controller/FrontController.php file and inside it find setMedia function.

There you can write your code to add JS for only home page.

$pagename = Dispatcher::getInstance()->getController();
if ($pagename  == 'index') {
$this->addJS(_THEME_JS_DIR_.'custom.js');
}

Add your JS in your theme JS folder and you will see your JS only in homepage.

If you can not find your JS loaded then remove cache/class_index.php file.

After it will be display.

Probably the easiest way without any override is to target the index.php page from the tpl files.

You can add it in any file, for example on the footer.

So I'll start targeting the index.php page and it's as easy as.

{if $page_name =='index'}
    <script type="text/javascript">
        $(document).ready(function() {
            $("a.linkscroll").on('click',function(event){
                event.preventDefault();
                var customoffset = 120;
                $('html, body').animate({
                    scrollTop: $($.attr(this, 'href')).offset().top - customoffset,
                }, 2000);
            });
        });
    </scrpt>
{/if}

You can see a live example here: JS Fiddle Example

With that your code should work and only in the home page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM