Jump to content

Script in tpl file not working


Recommended Posts

Hello,

 

I'm trying to add the following script to the header.tpl file, but it's not working:

 

{literal}
<script>
$(document).ready(function() {
    if ($(".shopping-cart-wrapper").is(".show")) {
        $("body").addClass('dropdown-is-open');
    } else {
        $("body").removeClass('dropdown-is-open');
    }
});
</script>
{/literal}

Basically, I want to check if the element 'shopping-cart-wrapper' has the class 'show' and toggle the class 'dropdown-is-open' for the body if it does. But it doesn't work. I tried using 'hasClass' instead of 'is' too, but no luck. I also tried using script = text/javascript but still nothing.

 

Where should I add this to make it work?

 

Thanks!

Edited by TheSmithsDoBusiness
code error (see edit history)
Link to comment
Share on other sites

instead of

  if ($(".shopping-cart-wrapper").is(".show")) {

use  hasClass(class_name) ->    hasClass( "show")    
not  hasClass(selector)        ->     hasClass(".show")

  if ($(".shopping-cart-wrapper").hasClass("show")) {

 

Edited by EvaF (see edit history)
  • Like 1
Link to comment
Share on other sites

ok, then check if the element with class "shopping-cart-wrapper" exists in the moment when you work with it
(let set javascript breakpoint  at the line

  if ($(".shopping-cart-wrapper").hasClass("show")) {

and check in  console

$(".shopping-cart-wrapper").length

 

Edited by EvaF (see edit history)
Link to comment
Share on other sites

$(".shopping-cart-wrapper").length

it returns count of html-elements with the selector ".shopping-cart-wrapper"

if you don't have experiences with javascript then add into your code js-alerts (  something as showmessage) this way:

{literal}
<script>
$(document).ready(function() {
    if ($(".shopping-cart-wrapper").is(".show")) {        
        $("body").addClass('dropdown-is-open');
        alert ('class dropdown-is-open added into body');
    } else {
        $("body").removeClass('dropdown-is-open');
        var classes = [];
        $( ".shopping-cart-wrapper" ).each(function( index ) {
          classes.push( index + ": " + $( this ).attr('class') );          
        });
        alert ($(".shopping-cart-wrapper").length ? classes.join (';'):  'no element has selector .shopping-cart-wrapper');
    }
});
</script>
{/literal}

if you don't see any message box, then check your code if some javascript errors doesn't occur

(mouse right button on page; in context menu the option "inspect" element )

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...