Styling for chosen or currently in use elements

Seeking assistance with creating a board using JavaScript and jQuery. The goal is for the user to select a cell (which adds an active class), then click on a different cell filled with a specific color, causing the original cell to fill in with the same color. Here is the relevant code:

http://jsfiddle.net/2J8yq/3/

var fillIn = $('.active_color_select')
$(red).click(function(){
 $(fillIn).css('background-color', 'red');
 });

** Suspecting an issue in this section

Upon testing, it was observed that after clicking an empty cell and selecting a color, the cell fills in correctly. However, choosing the next color results in all cells changing to the same color. Guidance is needed to ensure that only the selected cell receives the desired color without affecting other cells upon selection of a new color.

Your valuable input would be highly appreciated!

Thank you

Answer №1

Let me show you how I would approach this:

$('.color').click(function(){
    var bgColor = $(this).attr('id');
    $('.active_color_select').css('background-color',bgColor);
});

UPDATE: Upon further reflection, Rick brings up a valid point. It might be more effective to extract the background color attribute directly from the clicked element, like so:

$('.color').click(function(){
    var bgColor = $(this).css('background-color');
    $('.active_color_select').css('background-color',bgColor);
});

Answer №2

You've already made a query for that specific element using the selector.

fillIn.css('background-color', 'red');

The variable fillIn represents the jQuery object retrieved from your selector query ($('.active_color_select'))

So the entire code snippet would appear as follows:

var fillIn = $('.active_color_select')
$(red).click(function() {
    fillIn.css('background-color', 'red');
});

If you wish to apply this to a set of elements, you could simplify it by doing something like this:

<div class="fill-me-in" data-color="red"></div>
<div class="fill-me-in" data-color="green"></div>

This way, you can make it more generic with the following code:

$('.fill-me-in').click(function(e) {
    var me    = $(this),
        color = me.data('color');
    me.css('background-color', color);
});

Answer №3

To change the color of only the td with class active_color_select, utilize $('.active_color_select') instead of $(fillIn):

$(red).click(function () {
    $('.active_color_select').css('background-color', 'red');
});

$(blue).click(function () {
    $('.active_color_select').css('background-color', 'blue');
});

$(green).click(function () {
    $('.active_color_select').css('background-color', 'green');
});

$(mint).click(function () {
    $('.active_color_select').css('background-color', '#9CBA7F');
});

$(white).click(function () {
    $('.active_color_select').css('background-color', 'white');
});

$(lightPurple).click(function () {
    $('.active_color_select').css('background-color', '#BF5FFF');
});

Furthermore, bear in mind that your variable is already a jQuery object, so there is no need to wrap it inside $() again.

For instance, you can use:

inactive.removeClass('active_color_select'); 

instead of:

$(inactive).removeClass('active_color_select');

The same principle should be applied to other variables.

View Updated Fiddle Here

Answer №4

Make sure to remove all active classes from your click handlers and deactivate them:

 $(red).click(function(){
    $(fillIn).css('background-color', 'red');
    $('.active_color_select').removeClass('active_color_select');
  });

You don't need multiple variables, just simplify it like this:

 $('#red').click(function(){
    $('.active_color_select').css('background-color', 'red');
    $('.active_color_select').removeClass('active_color_select');
  });

You can chain the calls together for even cleaner code:

 $('#red').click(function(){
    $('.active_color_select').css('background-color', 'red')
                             .removeClass('active_color_select');
  });

Also, consider adjusting the extent of your initial click handler:

$('.inactive').click(function(){
      $('.active_color_select').removeClass('active_color_select');
      //optionally you could add inactive back to the above
      $(this).addClass('active_color_select');
      //optionally you can remove inactive from this
}) //close click handler here 

Answer №5

Check out this optimized code snippet that efficiently achieves the desired functionality: Optimized Code

// Select all fillable elements using a faster method than direct child selector
var fillableElements = $('#master').find('td');
var colorElements = $('#selection').find('.color');

// Variable to store currently selected elements
var selected = null;

// Using .on() for click events on dynamically added elements in the future
fillableElements.on('click', function() {
    var el = $(this);
    // Remove 'active_color_select' class from all other elements
    fillableElements.removeClass('active_color_select');
    // Add 'active_color_select' class to the clicked element
    el.addClass('active_color_select');    
    // Store the selected element
    selected = el;

});

colorElements.on('click', function() {
    var el = $(this);
    // Get background color of chosen color
    var color = el.css('background-color');
    // Apply the color to selected element
    selected.css('background-color', color);
});

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

Retrieve the link's "href" attribute and its text if they match the specified text

Is there a way to extract the href link and text from a specific type of link? <a href="google.com">boom</a> I am looking to retrieve only the 'google.com' part and the text 'boom' Furthermore, how can I filter out other ...

How can I position two bootstrap tables side by side based on their columns

Currently, I am utilizing bootstrap and Laravel form control to generate the table structures below. The one issue I am encountering is figuring out how to align the delete and edit buttons from two separate tables. Here is a snapshot of the current layout ...

Mastering the Art of Utilizing content_for and Rendering Partials in Rails 4

Recently, I discovered the power of utilizing content_for and found it to be incredibly useful. It may seem like I am making things more complicated than necessary, but my objective is: To create a custom header for the products#index page. As of now, I ...

Find the location of the div element but ignore any divs with a certain class

<div class="center"> <div id="ContentTop" class="tt1">Top Content</div> <div id="abc" class="hide">exrt</div> <div id="bcd" class="hide">Content exta</div> <div id="MidContent" class="tcg">Mid ...

Toggling reverses multiple CSS keyframe animations

I've been working on a unique animation to switch my website between dark and light mode. The animation is quite complex, so I anticipate that the solution will be equally intricate. Currently, I am toggling between classes, but this approach makes i ...

jQuery - Wait for the completion of one UI change before initiating another UI change

Is there a way to implement the functionality where $("#login").toggle("drop", {direction: "left"}); is executed first and upon completion, $("#register").toggle("drop", {direction: "right"}); is then carried out? The issue arises from the fact that the ...

Manage the placement of elements using CSS

Having an issue here. The blue-colored elements are showing up vertically, but I want them to be displayed horizontally. I've tried various methods but haven't been able to solve the problem. Providing just the code for the items below due to len ...

Toggle the display of slide numbers in RMarkdown xaringan / reveal.js presentations

In preparation for a workshop, I am creating HTML slides using the xaringan package in R, which is based on remark.js. These slides are made with RMarkdown, and while this approach has been effective, I have encountered a need to disable slide numbers on s ...

How does Facebook access the new hashtags when they are clicked on?

I've been developing a website recently and I'm really impressed with the way a popup page appears when you click on a hashtag. I've been wanting to incorporate a similar feature for a while now, but I'm not sure how to do it. Could thi ...

Leverage the power of jQuery to display JSON data retrieved from a PHP

I am having trouble with my jQuery AJAX call on a PHP page that outputs JSON. Despite my code seeming correct, the alert() dialog isn't showing and the JavaScript console isn't providing any errors. Can you help me identify what is causing this i ...

The dilemma with automated clicking in jQuery

I have recently developed code that, when an image is clicked, automatically clicks a link in the navigation bar. The code for this action is shown below: $('body.node-4 div#block-views-Poster-block_1 img.imagecache-Posters').addClass('manua ...

Combining different HTML table borders

Here is some example code: <!DOCTYPE html> <html> <body> <h4>Creating a table with nested tables:</h4> <table border="1"> <tr> <td>100</td> <td>200</td> <td> </td> < ...

JQuery - ToggleMenu - 3 different menus nested under 3 separate div containers

Currently, I have three menu buttons displayed horizontally. When one button is clicked, three links slide down below it. Clicking on another button will slide up the first set of links and slide down a different set. (view example here) My goal is to hav ...

What is the best way to continuously update a table row based on a database condition

I am working on a table that dynamically adds new rows via AJAX. _group.html.erb <%= content_tag_for(:tr, @group, class: 'group-new-row') do %> <td><%= group.title %></td> <td><%= group.owner_id %>< ...

Issue with binding the deepest level grid in a two-level deep Kendo Grid detail template

Encountering an unusual issue with the Detail Template in Kendo Grid. My setup includes two levels of Detail Templates, which have been functioning correctly most of the time (although it sounds peculiar). However, there are instances where the innermost g ...

Is there a method, like using jQuery, to insert `<br>` tags into each line of a dropdown select list?

I need help with implementing a select tool in a limited horizontal space with each line containing a lot of information. I attempted to embed a tag into the line but it didn't work. Are there any solutions available that could provide a simple fix ...

Looping the jQuery Ajax success function

Utilizing Ajax to input an array of data into a database. At the moment, when clicking on "#bookingbutton," it triggers a return block of HTML containing the ".select-room-button" button. I have incorporated the code for ".select-room-button" within the ...

Achieve the effect of "background-attachment: fixed" using a div element

I am attempting to replicate a similar effect as seen here, which is accomplished using the CSS property background-attachment:fixed. However, I want to achieve this effect using div elements instead. For instance, could I apply this effect to an h1 tag? ...

Ensure that a bootstrap table's cell occupies the entire available space, while also allowing for scrolling when there is overflow

Many questions have been raised about Bootstrap, Tables, and responsiveness. However, I have yet to find one that addresses my specific issue with getting a particular cell (<td> element) to: (a) Fill the available space, stopping at the window boun ...

What causes the disappearance of connecting lines after pushing content into a tab?

I have been using a jquery-connections framework to establish connections between elements on my webpage. However, I encountered an issue where the connectors disappear whenever I insert content inside the Tab. Upon including the following code: <div ...