0

I want to load an image background inside a specific div instead of <img src=""> tag using Javascript.

As it is now the code with the <img/> tag is:

item.prepend($('<img/>', {src: file[options.baseUrlAttribute] + '' +file[options.pathAttribute]}));

I tried something like that:

item.prepend($('<div style="background:url('file[options.baseUrlAttribute] + ''      
+file[options.pathAttribute]}')no-repeat center center / cover"></div>' ));

But it doesn't work and returns an error.

What is the correct syntax to make it work?

3
  • can you tell us what the resulting html is? From the looks of it, you're creating an empty div, and prepending it to an item, so it won't have any height. Commented May 24, 2021 at 14:07
  • 2
    item.prepend($('<div style="background:url(' + file[options.baseUrlAttribute] +file[options.pathAttribute]+')no-repeat center center / cover"></div>' )); Commented May 24, 2021 at 14:09
  • @Kinglish this worked fine can you post it as answer so i can select it as the worked answer? Commented May 24, 2021 at 14:12

1 Answer 1

2

It's easy to miss typos in long concatenated statements. The fixed code is:

item.prepend($('<div style="background:url(' + file[options.baseUrlAttribute] +file[options.pathAttribute]+')no-repeat center center / cover"></div>' ));

Or broken down for easier reading

const url = file[options.baseUrlAttribute] +file[options.pathAttribute] ;
const tag = '<div style="background:url(' + url + ')no-repeat center center / cover"></div>';
item.prepend(tag);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.