Using JQuery to apply span elements to images

Struggling to create a Pinterest-like webpage using masonry.js? Having trouble appending unique descriptions to each image in your code? You're not alone. The last line of the code seems to be causing issues, but the solution isn't clear. By consolidating all description tags into one span for each image, you may be missing out on individualized details.

Looking at various StackOverflow inquiries like jQuery: Add element after another element and add image/s inside a div with jquery, but haven't found a resolution yet.

View the entire pen here: http://codepen.io/OG/pen/VLEXgz

HTML

<body>
    <h1>Camper Stories</h1>
    <div id="content"></div>
</body>

CSS

h1{
    text-align:center;
    font-family: 'Lobster', cursive; font-size:80px;
    color:purple;
}

#content {
    width: auto;
    margin: 0 auto;
}

.item {
     display: inline-block;
     float: left;
     width: 300px;
     height:300px;
     margin: 2em;
     position:relative;
}

.item img {
    width: 300px;
    height: auto;
}

JS

var url = 'http://www.freecodecamp.com/stories/hotStories';
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        var myArr = JSON.parse(xmlhttp.responseText);
        myFunction(myArr);
    }
}
xmlhttp.open("GET", url, true);
xmlhttp.send();

function myFunction(arr) {
    var i;
    var headlines = [];
    //loop through json get need attributes
    //for(i = 0; i < arr.length; i++){
    for (i = 0; i < 5; i++) {
        var headline = arr[i].headline;
        headlines.push(headline);
        var authorImg = arr[i].author.picture;
        //console.log(img);
        //error function
        //if there is no thumbnail link the get author image
        if (img === "") {
            $('#content').append('<div class="item">' + '<a href="' + link + '">' + '<img id="myImg"  src="' + authorImg + '" alt="' + headline + '"    />' + '</a>' + '</div>');
        } else {
            //if there is a thumbnail image then use that image
            $('#content').append('<div class="item" id="hi">' + '<a href="' + link + '">' + '<img id="myImg"  src="' + img + '" alt="' + headline + '"    />' + '</a>' + '</div>');
            //if there is a 404 error with loading the thumbnail image then use author's image
            $('img').one('error', function () {
                this.src = '' + authorImg;
            })
        }
        $(arr[i].headline).insertAfter("img");
    }
}

Answer №1

Check out this link to see if it matches your requirements. Do you want to add the headline below the image?

$("<span>" + arr[i].headline+"</span>").insertAfter($("img").eq(i));

Answer №2

Creating elements in a structured manner can greatly improve the readability and maintainability of your code.

var wrapper = $("<div />");
var link = $("<a />");
var img = $("<img />");
...

After building the elements, remember to add any necessary attributes and classes before appending them together.

link.append(img);
wrapper.append(link);
...

This approach makes it easy to make modifications later on, such as appending a span to an image for adding descriptions.

Here's an example code snippet that demonstrates this process:

function createElements(data) {
  if(typeof data === "undefined") return; // handle error case
  for (var i = 0; i < data.length; i++) {
    var item = data[i];
    var upVote = item.rank;
    var href = item.link;
    var image = (item.image === "") ? item.author.picture : item.image;
    var headline = item.headline;

    // Initialize elements
    var wrapper = $("<div />");
    var link = $("<a />");
    var img = $("<img />");
    var description = $("<span />");

    // Add attributes and classes
    wrapper.addClass("item");
    link.attr("href", href);
    img.attr({"src": image, "alt": headline});
    description.text(headline);

    // Append elements to each other
    link.append(img);
    wrapper.append(link, description);

    $("div.content").append(wrapper); // Attach elements to the DOM
  }
}

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

Display JSON values from a successful AJAX call within an HTML dropdown menu

Having an html form with multiple drop down selections, I have utilized the same form for data editing, To edit data in a specific row of the table, I implemented an AJAX request. Once a row is selected and the user clicks on edit, the AJAX call retrieves ...

SPRING --- Tips for sending an array of objects to a controller in Java framework

Can someone help me with this issue? I am using AngularJS to submit data to my Spring controller: @RequestParam(value = "hashtag[]") hashtag[] o The above code works for array parameters but not for an array object. This is my JavaScript script: $http ...

Error message: Unauthorized request error with the change.org JavaScript API

I am currently working on integrating the javascript API from change.org in order to retrieve all of my signed petitions for display on my source forge page. However, I am encountering an unauthorized request response from the change.org API. Despite tryi ...

Creating dynamic visual elements on a webpage using HTML: Video

As I continue to learn HTML, CSS, and JavaScript to create a basic website for educational purposes, I have successfully embedded a video stored in my drive using the video element on an HTML page. However, I now aim to also display the video's title, ...

Is there a way to extract the value of Span and then store it in a Database?

I am currently facing an issue with retrieving the value of a span element. After selecting an item, the total price should be displayed in the span element, but I am having trouble implementing this using ajax. As a beginner in ajax, I am struggling to ge ...

Disable input with Safari colored background and transparency

Why does the CSS color #b3b3b3 turned white on a disabled input? What could be causing this and how can it be fixed? Take a look at this code snippet: https://jsfiddle.net/esty6t20/ CSS: .transp { background-color: transparent; } .bug-color { color: ...

Experiencing an Issue Getting an Undefined Value When Selecting a Radio Button

Struggling to extract the value from a user's selection of one of three radio buttons. Currently, my code is returning undefined, and I'm unsure about the reason behind this issue. This is the HTML structure: <div class="tab-pane fade in act ...

Check if a given string conforms to the JSONATA expression format

Here's the scenario: A user inputs a JSONATA expression into a form field. The form should show an error message if the entered JSONATA expression is invalid. Is there a regular expression or pattern that can determine the validity of a string as a ...

Applying VueJS filters to refine object values

Is there a way to verify if the value of "startAt" is present in an object and return its corresponding ID? Here is the object in question: [{ "id": "1234567", "createTimestamp": "2020", "name": { "action": "", "allDay": false, "categor ...

TCPDF's background color feature

Is it feasible to color the cell of a TCPDF table only if it contains data? In the image provided, I am looking to shade the blocks in gray if they have data. Please refer to the following code image for more details: https://i.sstatic.net/Qm2WV.png ...

Clear results if no filter input is provided

Currently, I have implemented a search as you type feature that replaces a DIV element populated by PHP. The functionality of the function is working fine; however, I am facing an issue where I cannot reset it to its original state if the input field is le ...

Capturing data from button inputs and the timing intervals between presses

I am currently facing a challenging ajax/php issue: In my project, there are 4 buttons that, when pressed, log the press event to a text file using a string representation. This string is named foo1 For example, if I were to press the first button 3 tim ...

Type property is necessary for all actions to be identified

My issue seems to be related to the error message "Actions must have a type property". It appears that the problem lies with my RegisterSuccess action, but after searching on SO, I discovered that it could be due to how I am invoking it. I've tried so ...

adjust the width of each individual cell in the table to create a varied layout

For my web app, I am working on a table that will contain multiple <tr> and <td> Here's the code snippet: <tr> <th style="width:30px;">date</th> </tr> <tr> <td>10-10-2016</td> </tr> E ...

"Effortless integration of JavaScript with PHP for streamlined database access

My current project involves working with a database table containing two fields - one for URLs and the other for descriptive text. These fields will be updated regularly by a separate script. The task at hand is to create a timer that checks the database ...

The process for restarting a jQuery slide show

Is it possible to pause and resume a JQuery-created slide show? $('#left_actual').cycle('stop'); //halt slideshow 1 $('#right_col').cycle('stop'); //suspend slideshow 2 $('#left_actual').cycle({ fx: ' ...

Issue with text input field causing the Enter key to not create a new line

In the example above, the text is placed in the middle of the text area. Here is the CSS code : .form-control { height: 300px; display: block; width: 100%; padding: 0.375rem 0.75rem; font-size: 1rem; font-weight: 400; line-heig ...

HTML5 - Transforming your webpages into interactive flipbooks

Is there a way to achieve a page-turn effect when loading external HTML pages into a div? I am interested in utilizing CSS3, HTML5 or jQuery for this purpose. ...

SQL - Extracting Information from HTML in a Column

I have a column named "Content". Within this column, there is HTML code containing various data. My task is to extract specific information from this HTML code and split it into five different columns: "Name", "Surname", "Email", "Telephone", and "Message" ...

How do you calculate the distance of a 3D model?

I am interested in creating a 3D model of a measuring tape similar to the one shown below: You can view the product image at this link: Link. They use Webgl, but not Three.js. Could someone provide instructions on how to create a measuring tape for a 3D ...