applying background image depending on html attribute when page loads

Currently, I am working on creating a div structure to add video content to my website. The setup involves using the vidurl for the video URL and srcpost for the background image and poster image when the video is selected.

I have encountered an issue where my code does not seem to work as expected. Despite searching online for similar cases, I couldn't find a solution. It seems like I may be missing something or not asking the question correctly. Initially, it was functional with the attr srcpost containing url("") within it, but I would prefer to eliminate that from the HTML if possible.

jQuery( document ).ready(function() {
   loadbgimg();
});

function loadbgimg() {
   $( '.video_selection' ).each(function() {
      var backgroundimg = $( this ).attr( 'srcpost' ).replace('%', ' ');
      $( this ).css('background-image', 'url(' + backgroundimg + ')');
   });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class='video_selection' vidurl='http://localhost/movies/Napoleon%Dynamite/napdyn.mp4' 
srcpost='http://localhost/movies/Napoleon%Dynamite/poster.jpg'>
<p>Napoleon Dynamite</p>
</div>

Answer №1

Great news! Your code is functioning perfectly! Take a peek below to see your script in action, along with some additional CSS and working images.

If you're encountering any issues, it's possible that the image path may be incorrect. Try visiting http://localhost/movies/Napoleon%Dynamite/poster.jpg in your browser to verify if the image is located there.

In case the image path is accurate, you might want to inspect the console using Chrome dev tools for further insights. Regardless, rest assured that the problem does not lie within your script. We hope this guidance proves useful!

jQuery( document ).ready(function() {
   loadbgimg();
});

function loadbgimg() {
   $( '.video_selection' ).each(function() {
      var backgroundimg = $( this ).attr( 'srcpost' ).replace('%', ' ');
      $( this ).css('background-image', 'url(' + backgroundimg + ')');
   });
}
.video_selection {
   padding: 10px;
   color: #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class='video_selection' vidurl='http://localhost/movies/Napoleon%Dynamite/napdyn.mp4' srcpost='http://placekitten.com/600/300'>
<p>Napoleon Dynamite</p>
</div>

<div class='video_selection' vidurl='http://localhost/movies/Napoleon%Dynamite/napdyn.mp4' srcpost='http://placekitten.com/800/300'>
<p>Another video</p>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Are there any alternative methods to define a constructor function in TypeScript that do not involve utilizing classes? Upon researching on this subject, it appears that all sources suggest using classes

Is it possible to transform this class declaration into a constructor function without losing TypeScript compatibility? class Animal { constructor(public name: string, public energy: string) {} } ...

What is the best way to display multiple "loading images" for each cell of a table's data as it is being fetched asynchronously from a PHP script?

I'm looking to enhance my website functionality by incorporating a box where users can enter a string and press the OK button. Once submitted, this data will be sent to the PHP backend which will then return 20 rows of results. However, each of these ...

Resolving the issue of "Cannot set properties of null (setting 'innerHTML') at HTMLInputElement.loader" involves identifying the root cause and implementing

Need assistance with this code. Although I believe everything is correct, it still isn't working as expected. The error mentioned in the title comes up whenever I try to use it. I've made multiple modifications to the code but it's still not ...

Trouble connecting: MongoDB Node.js client hangs during connection attempt

The node-mongodb-native for node.js seems to be causing a hang when using MongoClient.connect(...), while the mongodb-client (shell command line) works fine in the terminal. Any ideas on what might be causing this issue? var MongoClient = require('mo ...

Update the text on a Button component using ReactJS

I am looking to update the text displayed on the Check All button to say Uncheck All after all the checkboxes have been checked. Below is my code. Any recommendations?” checkAllCheckBox = () => { let {todos} = this.state let newArray = [.. ...

Having trouble toggling the navbar on and off in mobile. Error message: Unable to read parentnode of undefined

When I try to make my mobile navbar full screen on a mobile device, the hamburger button works as expected when clicked. Initially, all the links are displayed in full page view, but once I click on a link, it disappears and takes me to the respective sect ...

adjusting the size of separate models within a unified structure

Recently, I created a 3D model of my hometown and I wanted to incorporate real-time data to adjust the height of the buildings. Initially, I loaded each building as an individual mesh and added it to the scene during setup. var threeObjects = []; var bui ...

Customizing Internationalization in Shiny Apps using DataTables Local Language Files

I'm looking to localize my datatable in shiny using an internationalization file, but I need to reference a local file on my computer as my VM has no internet connection. How can I make this work? I attempted to follow the steps outlined here . Howev ...

Utilizing AJAX to submit an array of form inputs and securely storing the data in MySQL using

I have a set of code below that has been functioning well for a single input field. However, I also have additional code that adds extra fields to the form when a div with id #addForm is clicked, and these inputs are named "itemName[]". <script> ...

Ways to adjust the size of a Primeng autocomplete with multiple selections?

I'm new to Angular and I'm attempting to adjust the width of a primeng auto complete component in order to fill the column of a table. I've already experimented with using style="width: 100%" but that approach hasn't yielded any result ...

If the image is not found, deactivate the anchor or hyperlink

I am encountering an issue where I have an image tag within an anchor element setup as shown below: <a href='$image'><img alt='No Image' src='$image'></a> When the image is not available, I can still intera ...

A guide to verifying a user's age using JavaScript by collecting information from 3 separate input fields

On page load, only the year input is required for users to fill in. The user can enter their birth year first without providing the month and day. Currently, I have a function that checks if a person is over 16 years old by comparing their birth year with ...

Cache Property: Unable to Retrieve Request in Current Context

After scouring all similar posts about the error message "Request is Not Available in This Context" on SO, it appears that my situation stands out. In our application, many pages inherit from a "base page" class (referred to as BP2) which itself inherits ...

CSS float layout for arranging boxes of varying sizes

I am having trouble organizing this layout with CSS and using floats on the divs. The layout consists of standard sized boxes, a large box, and a tall box. Here is the link to the jsfiddle for reference. Here is the markup I am working with - <head> ...

Increase the size of the parent div as the height of the position:absolute child div grows

I am facing an issue with a parent div and its 2 child divs. <div id="parent"> <div class="child1 col-2"></div> <div class="child2 col-10"></div> </div> The child1 div has absolute positioning a ...

Using ReactJs to merge multiple style objects in an immutable way

My inline style object looks like this: const simpleCarousel = { toggle: { .... }, toggle_prev: { left: 0 }, toggle_next: { right: 0 } }; Here is the standard CSS markup I am working with: <div className="toggle, toggle_ ...

Guide on setting up Facebook Ads for IOS with React Native

I'm encountering an issue in React Native while attempting to launch my app on IOS, where a warning message is displayed: "Module AdChoiceManager requires main queue setup since it overrides 'init' but doesn't implement 'requiresM ...

Exploring trees with jQuery: A guide to traversal techniques

<ul id="org" style="display:none"> <li id="visited"><a href="#" class="ui-link">ROOT</a> <ul id="main_child_ul" class="children"> <li><a href="#">Acura</a> & ...

Troubleshooting a Jquery Ajax Problem

Currently, I am developing a feature for my project that involves creating popup windows for tips. Once the user clicks on the 'turn on tips' button, these windows are supposed to appear next to specific elements. However, I encountered an issue ...

What is the process for accessing extra scope information with next-auth?

I have integrated next-auth with Discord authentication and included guilds in my scope, but I am unable to retrieve the guild data. How can this issue be resolved? const options = { providers: [ Providers.Discord({ clientId: process.env.DISC ...