user47143
user47143

Reputation: 75

create an array of images by pulling them from html

I have a table of images all with the class .pics and I want to use Javascript to pull the actual pictures from the HTML table and put them into an array.

After that I want to randomly select an image from the array and change its brightness level.

I tried doing this:

var allPics = [];

$(".pics").each (function (){ allPics.push (this); }); 

but no dice.

Thanks!

Upvotes: 0

Views: 259

Answers (1)

Jonathan
Jonathan

Reputation: 11494

First we initialise the array with var allPics = [];

Then traverse our HTML and load the array.

$('.pics .pic').each(function() {
    allPics.push(this);
});

Then generate a random index based on the size of the array.

var index = parseInt(Math.random()*allPics.length);

Then spew out the images stored in the array, using $(allPics[index]).prop('outerHTML') to convert the jQuery object to an HTML string.

$('.random').append(
    $(allPics[index]).prop('outerHTML')
);

The image brightness is adjusted in CSS with filter: brightness(.5), be sure to use at a minimum the -webkit- vendor prefix, as a lot of the major browsers at the moment require this at the moment.

Please see my fiddle for the working example.

Upvotes: 1

Related Questions