Magento 2.1 JavaScript Snippet Implementation in .PHTML File

javascriptjquerymagento-2.1

I want to insert a JavaScript snippet in a Magento .phtml template file. Please, refer to the following question to review the JS snippet – it is the snippet of the chosen best answer:

$(function() {
var menu = $('#fixedbtn');
function isInViewport($this) {
   var elementTop = $this.offset().top;
   var elementBottom = elementTop + $this.outerHeight();
   var viewportTop = $(window).scrollTop();
   var viewportBottom = viewportTop + $(window).height();
if(elementTop < viewportBottom ==true){
    menu.addClass('fixedPosition');
}else { 
    menu.removeClass('fixedPosition');
 }
}
$(window).scroll(function() {
isInViewport($('#footer-1'))
});
});

Now, this code works perfectly in a standard HTML file on a non-server environment. However, when I tried to implement it in a Magento website, it just doesn't work. I tried including it in my app.js, then tried placing it on the page itself between script tags. I tried replacing the $ with jQuery, alas, nothing seems to work.

How can I implement this JavaScript code in Magento template file? Could you please guide me in how I need to format the code, so that it works in Magento (2.1.8)?

Follow up:

Alright, at this point I'm quite unsure why the above code will not work as inline script on Magento .phtml template file. I've used JavaScript in this Magento set-up before, both in app.js and also as inline script all working fine. Here, for example, I have the following JS code snippet in copyright.phtml working just fine:

<script type="text/javascript">
jQuery(function() {
    jQuery(window).scroll(function() {
    if(jQuery(this).scrollTop() > 800) {
        jQuery('#back-top').fadeIn(); 
        jQuery('#back-top').style.display = "block";  
    } else {
        jQuery('#back-top').fadeOut();
        jQuery('#back-top').style.display = "none";
    }
});
   jQuery('#back-top').click(function() {
    jQuery('body,html').animate({scrollTop:0},500);
});   
});
</script>

I also added the following script inline:

<script type="text/javascript">
require(['jquery','domReady!'], function($){
console.log('hello world');
})
</script>

And "hello world" comes out as output in console upon page reload = so no problem with caches or script parsing. I place the desired JavaScript code within

<script type="text/javascript">
require(['jquery','domReady!'], function($){
..desired code snippet here.....
})
</script>

Reload page, and… it does not work. Odd? Any idea why?

Best Answer

Try to cover it with:

<script>
    require([
        'jquery',
        'jqueryui'
    ], function ($) {

   ... Your code ...

    });
</script>

That's how to place script inside .phtml. Another option to include it with requirejs. Google it.

Related Topic