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>
3

2 Answers 2

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

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

Comments

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

2 Comments

thank you @Rohan Kumar this is what i needed people did not understand me. thank you
$(html+','+ bg)? I would prefer html.add(bg) or bg.add(html)

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.