0

I want to create something when clicking on the image inside the div element. It should change it's color to blue, alongside changing the background color to blue. Is the code I am writing correct? Because it's not working properly. Also, is there a better way to apply CSS to elements?

FIDDLE

var photo = $('#photo');
var html = $('html');
var bg = $('#bg');
$(photo).on('click', function(){
  $(this).hide()
  .delay(600)
  .fadeIn(300);
  $(html, bg).css({
    background :'blue'
  });
});

html

<div id='bg'>
    <img id='photo' src="http://img.pixland.uz/u11878f337693s.jpg" alt="" />
</div>
Tukhsanov
  • 301
  • 1
  • 3
  • 15

2 Answers2

3

As well as Rohan Kumar's answer, which is of course wholly correct, there is a method for combining jQuery selections: $.fn.add. You can pass an HTML element, an array of elements, a jQuery selection, a jQuery selector or an HTML string to it. In this case, we could pass one of the jQuery objects you created:

In this case you could do the selection with html.add(bg):

var photo = $('#photo');
var html = $('html');
var bg = $('#bg');
photo.on('click', function(){
  $(this).hide()
  .delay(600)
  .fadeIn(300);
  html.add(bg).css({
    background :'blue'
  });
});

jsFiddle

Community
  • 1
  • 1
lonesomeday
  • 233,373
  • 50
  • 316
  • 318
2

You are using photo as jquery object so no need to use a $ for photo again, or try it like,

var photo = '#photo';
var html = 'html';
var bg = '#bg';
$(photo).on('click', function(){
    $(this).hide()
    .delay(600)
    .fadeIn(300);
    $(html+','+ bg).css({
    // to make multiple selectors into a single one
        background :'blue'
    });
});

Refer multiple-selectors for more details

Live Demo

Rohan Kumar
  • 40,431
  • 11
  • 76
  • 106