Search code examples
javascriptarraysimagehyperlinkhref

Adding a link to an image in an array


I have an array list that is working perfectly fine except I am falling short of modifying one little part.

I'd like to have the image I am using in the array to to have the associated link of docSrc. I have notes in my code.

<html>
<head>
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script>

window.onload = function() {

var docs = [
{
    docTitle: "onesider number 1",
    docInfo:    "its onesider number 1",
    docSrc: "http://www.google.com",
    docImg: "http://www.youthedesigner.com/wp-content/uploads/2011/05/cool-car-designs-13.jpg"
},
{
    docTitle: "onesider number 1",
    docInfo:    "its onesider number 1",
    docSrc: "http://www.google.com",
    docImg: "http://www.youthedesigner.com/wp-content/uploads/2011/05/cool-car-designs-13.jpg"
},
{
    docTitle: "onesider number 1",
    docInfo:    "its onesider number 1",
    docSrc: "http://www.google.com",
    docImg: "http://www.youthedesigner.com/wp-content/uploads/2011/05/cool-car-designs-13.jpg"
},
{
    docTitle: "onesider number 1",
    docInfo:    "its onesider number 1",
    docSrc: "http://www.google.com",
    docImg: "http://www.youthedesigner.com/wp-content/uploads/2011/05/cool-car-designs-13.jpg"
}
],

// This my items container  
container = $('#documents');


$.each(docs,function(i,doc){

// Let's create the DOM
var item = $('<div>').addClass('item'),
    title = $('<h1>'),
    info = $('<div style="background-color:#ff0000;">'),
    link = $('<a target="_blank">'),
    img = $('<img>').addClass('header');

// Add content to the DOM
/*link.attr('href',doc.docSrc)
.text(doc.docTitle)
.appendTo(title);*/ /// This works fine for DocTitle

/* This is the part that I am not able to figure out.  I know I shouldn't be using text but I do not know my other options. */
link.attr('href',doc.docSrc)
.text(doc.docImg)
    .appendTo(img);

info.text(doc.docInfo);
/*img.attr('src',doc.docImg);*/

// Append the infos to the item
item.append(img,title,info);

// Append the item to the container
item.appendTo(container);
});


//code here
}
</script>

<style>
#documents {
padding: 0px;
width:100%;
}

.item {
background-color: #dedede;
padding: 10px;
margin-bottom: 20px;
}
.header {
position:relative;
margin: 0 auto;
background-color:#6699FF;
width:100%;
border-radius:5px;
}
</style>
</head>

<body>
<div id="documents"></div>
</body>
</html>

I know this ".text(doc.docImg)" has to be wrong because I keep getting the text displaying rather than an image-link. I want my image to appear as a link.

Any support is appreciated.


Solution

  • You probably want to append the img to the a. If you want to add docSrc as images' src then do img.attr('src', doc.docSrc); before this:

    link.attr('href', doc.docSrc)
        .text(doc.docImg)
        .append(img);
    
    item.append(link, title, info);