When it comes to assigning a background to a div using jQuery and JSON

I have been experimenting with creating a database using only JSON and surprisingly, it worked once I added a "js/" in the URL. However, my current issue lies with CSS. Let me elaborate.

Here is the JSON data:

[
    {
        "title":"Facebook",
        "url":"http://www.facebook.com",
        "bg":"../img/facebook.png"
    },
    {
        "title":"Twitter",
        "url":"http://twitter.com",
        "bg":"../img/twitter.png"
    }
]

This is the HTML markup:

<section id="links">
           <!-- anchor tags should go here -->
</section>

And this jQuery code snippet:

$(function(){
    $.getJSON('js/links.json', function(data){
        $.each(data, function(index){
            $("#links").append('<a href="'+data[index].url+'" style="background-image:url("'+data[index].bg+'");"><span>'+data[index].title+'</span></a>');
        });
    });
});

You would expect it to work perfectly fine. It does display the content, but for some reason, the background image is not showing up. The HTML seems to be behaving strangely as shown in the inspector.

So, what could be causing this issue and how can I rectify it?

Answer №1

It seems like the issue might be related to how you've specified the style attribute.

style="background-image:url("'+data[index].bg+'");

The quotation mark immediately following the opening parentheses is terminating your style attribute. Simply removing it could potentially resolve the problem

style="background-image:url('+data[index].bg+');

Alternatively, you could try replacing the double quote with an escaped single quote for a potential solution

style="background-image:url(\''+data[index].bg+'\');

Answer №2

It's important to use backslashes to escape double quotes when needed: **\**

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

Prevent loss of data when user incorrectly submits a webform

Currently, I am working with Wordpress and a contact form plugin which is based on php. The form provided by the plugin is quite lengthy and my client has requested that the data entered by users should not disappear if they make a mistake and need to co ...

How can we manage a discovered item in Promise and Recursion scenarios without relying on a callback function?

I need to iterate asynchronously and recursively over a folder hierarchy on the server. When a file is found, I want to call a custom method. Here's my current code structure: searchFile(root, handleFile); // recursively loop through folders and ha ...

Guide to switch background image using querySelector

I am currently trying to figure out how to set the background image of a div block by using querySelector. I have attempted various methods in my test code below, but unfortunately none seem to be working. Can someone please provide assistance? <!DOC ...

Avoiding Vue Select from automatically highlighting the initial option: tips and tricks

Currently utilizing Vue Select as a typeahead feature that communicates with the server via AJAX. By default, the first option from the server response is highlighted like this: https://i.stack.imgur.com/jL6s0.png However, I prefer it to function simila ...

Unraveling JSON string containing additional double quotes in Python

Does anyone know how to handle parsing a poorly formatted JSON String in python? Take a look at this example: "{""key1"":""value1"",""key2"":{""subkey1"":null,"&qu ...

Center alignment is not being applied to the SVG element

I am currently working with React and when my component renders, it displays an SVG inside a div. Here is a snippet of the code: render() { return( <div class="myClass"> <svg> ... </svg> </div> ); ...

jQuery Typeahead implementation malfunctioning when text matches either the first or last character

It seems like there is a problem with the .split() method, especially when the characters match the beginning or end of a name. To see the issue in action, visit this JSFiddle link: http://jsfiddle.net/5uebxvex/ I'm working with the Employees tabl ...

Exploring the getJSON function within jQuery

{ "Emily":{ "Math":"87", "Science":"91", "Email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1d6f7e767c51767b727e737f764f747879">[email protected]</a>", "City":"Chicago" }, "Sa ...

What causes the left click to not trigger in Kendo's Angular Charts?

My homepage features a simple bar chart that displays correctly, but I am having trouble capturing the left click event (the right click works fine). This is an example of code from my template: <kendo-chart *ngIf="(dataExists | async)" [ ...

Cordova on iOS experiences an immediate error and HTTP status code of 0 when attempting an Ajax call, resulting in a failure with

For the past 3 weeks, I have been struggling with an issue that seems to have no solution. The problem occurs when using Cordova, as my ajax calls return immediately after being triggered. The error message appears right below the sending message in the lo ...

Utilizing Vue and Websockets for seamless communication: Managing the exchange of messages between users

In an attempt to create a messaging system that shows alerts of messages to different users, I have implemented Vue Socket Io from https://www.npmjs.com/package/vue-socket.io. However, the issue lies in the fact that the alerts are not being triggered as e ...

Looking for a logo placed in the center with a top fixed navigation using Bootstrap

I am in need of a Centered Logo using Bootstrap fixed top navigation. The goal is to have the brand centered within the navigation. Check out my Sample Fiddle .LandPageNavLinks { list-style-type:none; margin:0; padding:0; } .LandPageNavLin ...

What is the process for adding an authentication token to a URL as a query parameter?

Currently working on implementing PayPal Express Checkout feature on my ASP.Net MVC site. This site utilizes token authentication, and I am attempting to include the token in the PayPal return URL as a query parameter. I have set up a handler that captur ...

Issue with express-validator returning undefined value on forms set to enctype='multipart/form-data'

Currently, I am developing a login authentication application using basic node.js+express. While extracting values (such as name, email, etc) from the registration page, I utilize express-validator for validation. However, I encounter an issue where all va ...

AngularJS: When the expression is evaluated, it is showing up as the literal {{expression}} text instead of

Resolved: With the help of @Sajeetharan, it was pinpointed that the function GenerateRef was faulty and causing the issue. Although this is a common query, I have not had success in resolving my problem with displaying {{}} to show the outcome. I am atte ...

Enable only a single radio button to be selected in HTML

I am facing an issue with my radio buttons where I only want one to be selected at a time. Despite giving them the same name, all four can still be selected simultaneously. <h1>Portion</h1> <input type="radio" name="portion_n ...

Creating an object that tracks the frequency of each element from another object using JavaScript

I have a scenario where I need to create a new object based on the number of occurrences of specific minutes extracted from a timestamp stored in another object. Existing Object: { "data": { "dataArr": [ { ...

Configurations for MongoDB document serialization

Is it possible to serialize only private fields of an object with DataMember attributes in MongoDB? string json = item.ToJson( new MongoDB.Bson.IO.JsonWriterSettings() { GuidRepresentation = GuidRepresentation.Standard ...

The Ajax Form disappears from the page

After racking my brain for a while, I've come to the conclusion that it's time to seek some assistance. I have work tomorrow and I don't want to spend all night on this. The issue lies in my form which is located inside a modal, here is my ...

Finding a specific element within a table using xpath in selenium proved to be a challenge

I am trying to click on a specific button inside a table where each row has an update button. Here is what my table looks like: <table _ngcontent-vhp-c82="" datatable="" id="dtOptionsComments" class="display table tabl ...