Reputation: 114
This may sound very dumb to many, but my brain is just stumped.
I have 10 links and would like a different image to load into a container each time a link is clicked. That doesn't seem to hard, right?
<div class="sidebar_content">
<ul>
<li><a data-file="CF6-80C0.jpg?v=1">CF6-80C0</a></li>
<li><a data-file="CF6-80C1.jpg?v=1">CF6-80C1</a></li>
<li><a data-file="CF6-80C2.jpg?v=1">CF6-80C2</a></li>
<li><a data-file="CF6-80C3.jpg?v=1">CF6-80C3</a></li>
<li><a data-file="CF6-80C4.jpg?v=1">CF6-80C4</a></li>
<li><a data-file="CF6-80C5.jpg?v=1">CF6-80C5</a></li>
<li><a data-file="CF6-80C6.jpg?v=1">CF6-80C6</a></li>
<li><a data-file="CF6-80C7.jpg?v=1">CF6-80C7</a></li>
<li><a data-file="CF6-80C8.jpg?v=1">CF6-80C8</a></li>
<li><a data-file="CF6-80C9.jpg?v=1">CF6-80C9</a></li>
</ul>
</div>
My container in the css is
.bom_container { position: absolute; width: 720px; height: 500px; border: 1px solid #000; }
So how do I get these data-files into my container? My JavaScripting skills are beyond new!
Upvotes: 0
Views: 868
Reputation: 101
working js fiddle
// jQuery syntactic sugar to run after page loads
$(function () {
// attach a click event to anything with a data-file attribute
$("[data-file]").on('click', function (evt) {
// figure out what was clicked
var clickedEl = $(evt.target);
// get the data-file attribute
var dataFile = clickedEl.attr('data-file');
var container = $(".bom_container");
// empty the div
container.empty();
// create image element
var img = $("<img/>").attr("src", dataFile)
// add it to the container
container.append(img);
// or update the background image
// container.css('background-image','url('+ dataFile +')');
});
});
Upvotes: 1
Reputation: 465
Case, if you want insert image as HTML element.
$(function () {
$('ul').on('click', 'a', function () {
$('div.sidebar_content').children('img').remove();
$('<img />').attr('src', $(this).data('file')).appendTo('div.sidebar_content');
});
});
Case, if you want insert image as background:
$(function () {
$('ul').on('click', 'a', function () {
$('div.sidebar_content').css('background-image', 'url(' + $(this).data('file') + ')');
});
});
Upvotes: 0
Reputation: 9397
$('li a').on('click', function() {
var imgSrc = $(this).data('file');
var img = document.createElement('img');
img.src = imgSrc;
$('.bom_container').append(img);
});
Upvotes: 0
Reputation: 64657
Detect the click, and set either the background image or the html content of the container:
$('a[data-file]').on('click',function(e) {
e.preventDefault();
$('.bom_container').css('background-image','url('+$(this).attr('data-file')+')');
//or, if you want to load it not as a background:
$('.bom_container').html('<img src="'+$(this).attr('data-file')+'" />');
});
Upvotes: 0