0

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!

4
  • There are less-verbose ways to get that array, but this seems fine, if the HTML is just as described. Can you show (a) the HTML of some of the images and (b) how you're attempting to change the brightness, or whatever else is failing? As it is, there's no way to know what might be going wrong. Commented Aug 19, 2015 at 18:35
  • the this will be HTML Image Object Element and not jQuery object. While randomly selecting $(allPics[x]) will give you a jQuery equivalent if you are failing there... Commented Aug 19, 2015 at 18:40
  • The above works just fine: jsfiddle.net/L7nzzmo0 Commented Aug 19, 2015 at 18:57
  • @user47143 do you need more help? If my answer was helpful to you and answered your question, please don't forget to accept that answer. Also see What does it mean when an answer is "accepted"? and Why is voting important?. Commented Aug 23, 2015 at 20:35

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.