Selecting CSS Properties with jQuery

I am trying to make an image change color to blue and also change the background color to blue when it is clicked inside a div. However, my code doesn't seem to be working as expected. Is there a more efficient 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>

Answer №1

Aside from the answer provided by Rohan Kumar, which is undoubtedly accurate, there exists a technique for merging jQuery selections: $.fn.add. This method allows you to input an HTML element, an array of elements, a jQuery selection, a jQuery selector, or an HTML string. You could utilize one of the jQuery objects you have created in this scenario:

In this instance, you could perform the selection using 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'
  });
});

Check out the demonstration on jsFiddle

Answer №2

When utilizing a photo as a jQuery object, there is no need to use a $ for the photo again. You can try implementing it like this:

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

For more information on using multiple selectors, you can refer to multiple-selectors.

Check out the Live Demo for a visual representation.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to incorporate an URL with AJAX in Yii framework?

Check Out This Page <script type="text/javascript"> $("#project").change(function(){ var data1=$("#project").val(); $.ajax({ type: "POST", url: "<?php echo Yii::app()->createUrl('ajaxfunc&a ...

Select elements in jQuery using both a specific selector and a negative selector

I am currently working with a JQuery function that highlights a specific word and scrolls to it: $('article.node--article p, .video-title').highlightWordAndScroll({ words : search_word, tag : '<span class="found_key ...

"Utilizing the power of Twitter Bootstrap and Snap.js for

I am currently working on integrating Snap.js by jakiestfu with Twitter Bootstrap. I have managed to make it work to some extent (I can slide the content and open a drawer through a click event). However, I am facing a challenge where the drawer content re ...

"Troubleshooting Why AJAX Update for CGridView is Not Functioning

I've encountered an issue with my CGridView grid where I receive an error every time I try to update it. Despite spending a lot of time trying to resolve this, I still haven't been able to figure out what's missing. Here's the code sni ...

What sets apart jQuery's `click`, `bind`, `live`, `delegate`, `trigger`, and `on` functions, and how can they be utilized differently in coding

I have gone through the documentation for each function provided on the official jQuery website, but I couldn't find any comparison listings for the following functions: $().click(fn) $().bind('click',fn) $().live('click',fn) $().d ...

Ionic 4: Facing issues with setting complete background image on ion-card

https://i.stack.imgur.com/3lH6h.png I'm currently attempting to set a background image for an Ion-card in order to completely cover the card's area. However, I'm facing an issue where the background image does not cover the entire area and ...

Morris.js tutorial: Enhancing bar charts with data labels

I have this: But I want this instead: Does morris.js support this feature? If not, what would be the most effective method to implement it? ...

The page switch with a jittery effect

Could really use some assistance with this code that has been giving me trouble for quite a while now. It's a simple HTML, CSS, and JS code involving two pages. [The second page overlaps the first by default, but adjusting the z-index of the first p ...

transmit JSON data with an AJAX request and receive a response

I'm looking to make a JSON request to an API and receive a response. I tested it using Postman and successfully received the following response: JSON request to API: { "apikey":"&^$%#@!jwebdpqodp9fgkwjebfkdpqihdqlwkndqp" } The response I receiv ...

Counting the number of elements in a list can be problematic when using Firefox

Currently, I am in the process of writing CSS to customize the appearance of an XML document. Specifically, I aim to alter how child elements are displayed and have them resemble HTML OL/UL/LI elements. The structure of my XML file is as follows: <?x ...

Hierarchy-based dynamic breadcrumbs incorporating different sections of the webpage

Currently in the process of developing a dynamic breadcrumb plugin with either jQuery or Javascript, however I am struggling to implement functionality that allows it to change dynamically as the page is scrolled. The goal is to have a fixed header elemen ...

Using jQuery to send LocalStorage data to an email address with the help of PHP

Currently, I am in the process of developing a basic eCommerce/checkout system. My goal is to utilize localStorage data and transfer it to PHP using jQuery or any other method that is convenient. However, when I attempted to send the email, I only received ...

The content within an iframe is inaccessible through JavaScript when the onload event occurs

My current project involves integrating a payment service provider with 3Ds, and one of the steps in the process requires following specific instructions: Upon receiving the response to your initial API request, extract an URL along with some data. Embed ...

"Handsontable organizes information pulled directly from the backend database using JSON/AJAX

In order to implement the Handsontable column sorting and direction indicators, I would like to create a mechanism that sends sort requests to my database and displays the corresponding results. Although the Handsontable sort plugin is effective in allowi ...

The login form for the MVC website will only auto-submit on IE

I have developed a cutting-edge MVC website that allows users to securely access specific information. However, I am encountering an issue with Internet Explorer - the browser seems to automatically submit the login form when users navigate to the login pa ...

- Challenges with internal systems

I have a dialog window where I want to display a confirm dialog when clicking Cancel. To achieve this, I am creating a div element with some text that should be shown in the confirm dialog. However, the issue I'm facing is that the text intended for t ...

Adding elements within a loop using jquery

I am currently working on adding a toggle button using Javascript. I want to include three span tags inside it as well. To achieve this, I am creating a span variable and attempting to append it within a basic FOR loop that iterates 3 times. Below is the ...

Executing SQL Query on Button Click Event

I am working with PHP and trying to execute a SQL query when a button is pressed. However, the issue I'm facing is that nothing happens when I click the button! I checked the developer console but there doesn't seem to be any action detected when ...

Encasing a series of AJAX calls in a function: Implementing JavaScript and JQuery

I am facing an issue with a chain of two AJAX requests within a forEach() loop, where the second request relies on the response of the first. I have tried to wrap this code block in a function for reusability, but it seems to stop working. As a beginner in ...

A simple guide on how to surround every incorrect input index in mapped inputs with red borders

I am incorporating a modal that corresponds each element of the object newCompanies to a specific row: {newCompanies.map((company, index) => { return ( <div> <div className="side- ...