I’m trying to retrieve an image from my assets folder dynamically. The process of my code is that when the element is clicked, its parent element will change background according to the name passed by the child elements ID. Please see my code below:
$(".flex-item").click(function () {
// add class to div while removing it from others with same class
$(".flex-item").removeClass("expand").addClass("vertical"); //declare the class of the element, remove expand class from all
$(this).addClass("expand").removeClass("vertical"); //add class to clicked element
var changebackground = $(this).attr('id'); //get id of clicked element
$("#vaq-key-features-img").css({
"background-image": "url({{ '"+changebackground+".jpg' | asset_url }})",
});
});
I have renamed my theme.js to theme.js.liquid. The url is being returned but the jquery variable is being read as a string and not displaying its value. See below:
<div class="container" id="vaq-key-features-img" style="background-image: url(https://cdn.shopify.com/s/files/1/1392/6087/t/3/assets/%22+changebackground+%22.jpg?8438893007511141278);"></div>
Is there something I’m missing?
2
Answers
I found a topic in the Shopify forum talking about passing a variable within the liquid filter and found out that it is not possible since liquid filters are server side language. I did a work around with my code by using jQuery
attr();
I have added a data attribute within may parent container which will hold the id-name being passed by the child divs.Select the div with specific data and change background by using css attribute selector:
Since css file and images are stored in the same Shopify asset folder, specifying the path using liquid filter is not necessary anymore.
Try something like this
I’ve used
ES6 template literal
.If you are using old browser where
ES6
won’t support then tryHope this will help you.