Updating the color of text inside columns using JQuery

I've been working on a webpage with three columns, each containing a group of squares representing different colors. When a user clicks on a color square in column 1, the text within that column changes to that color. The same goes for columns 2 and 3.

Since I'm new to jQuery, I'm not sure if my approach is the most efficient way to achieve this effect. I'm wondering if there's a better way to implement this functionality. Is it possible to have just one CSS style called 'picker' for all color changes in each column? And can the jQuery code be optimized so that it's not split into three separate functions?

Any advice or suggestions would be greatly appreciated!

Answer №1

Absolutely! You can reuse CSS selectors to make your code more efficient. Avoid creating redundant classes with the same attributes and values!

Consider using classes like .grid, .container, .selector for better organization.

Instead of relying on div IDs, try utilizing jQuery to target elements dynamically based on event triggers or using $(this).

Take a look at this demo on jsFiddle: http://jsfiddle.net/ABC123/4/

Answer №2

If you're looking for a solution, you can test out this method:

$(function () {
    $('.picker').css('background-color', function () { //This sets the background color for each picker square.
        return $(this).data('color'); //Retrieve the color from the data attribute
    }).click(function () { //Chain it through for the click event
        $(this).closest('.content').css({ //Identify the parent content element where the color should be applied
            color: $(this).data('color') //Assign the clicked picker's color to the content
        });
    });
});

Check out the Demo Here

In your markup, add a class named content to easily recognize its parent content.

<div class='col2 content' id="test1"> <!-- You don't need an ID if you are using this for selection. 

Get rid of all the CSS rules for picker1 and picker2, and stick with just picker.

By using closest, you can ensure that even if you decide to include a wrapper around your picker, your actual content div will still be targeted.

Answer №3

Indeed, there is a solution to your question. Simply update all classes (picker1, picker2) to be picker and remove the IDs (test, test1..)

Give this a try:

   $('.picker').each(function(){
      var myColor = $(this).data('color');
      $(this).css({background: myColor })
   });
  $('.picker').click(function(){
     var myColor = $(this).data('color');
     $(this).parent().css({color: myColor});

  });

IMPORTANT: The click event does not need to be inside the each loop.

Check out the fiddle here

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

How can React Portals help address challenges?

After reviewing the information from the react portal documentation: A common scenario where portals are useful is when a parent component has styling like overflow: hidden or z-index applied, but you want the child component to visually extend beyond i ...

Updating the span element upon click in jQuery

I have this JavaScript code snippet that I am working with: $('a').click(function() { $('a span').first().toggleClass('hide'); $('a span:nth-child(2)').toggleClass('display'); }); .hide { display:none; ...

Ways to add stylistic elements to variables using JavaScript

I'm currently working on an API and I've managed to get it up and running, but now I'd like to add some style to it. I've been attempting to change the style for variables such as title, country, status, and summary but haven't ha ...

Should I be concerned about including a non-existent CSS class?

When it comes to using jQuery and finding the values of text fields, adding classes seems like a common practice. However, I am concerned about how this may impact page loading. Is it efficient for the browser to search for all these classes? In the past, ...

Utilizing loops for data selection and presentation within a div using MySQL and PHP

I currently have a large table in my MySql database containing numerous rows of records (referred to as the existingbankproducts table): https://i.sstatic.net/jQzd3.png Below is the code I am using to select data from the database: $stmt2 = $DB_con-> ...

Error in AngularJS ngRepeat Syntax

While using AngularJS v1.3.15 I encountered a strange syntax error: http://errors.angularjs.org/1.3.15/ngRepeat/iexp?p0=item%20asNaNtems This is the code snippet from my template (templateUrl): <div class="context-menu" ng-if="showMenu"> &l ...

A bot responsible for assigning roles never fails to remove a role when necessary

My goal was to develop a bot that automatically assigns users a role based on the language they speak in a bilingual server. However, when I tried to assign myself the Czech role, it added the role but failed to remove the rest: const Discord = require(&a ...

How can I properly integrate multer with Node and Express in this situation?

I've been working on setting up a route for uploading photos, but after making some changes, it has stopped functioning and I'm not sure how to fix it. const multer = require('multer'); // MULTER STORAGE const multerStorage = multer.di ...

Implementing an event listener on an anchor element dynamically inserted through Javascript

I made an Ajax call that retrieves a list of movie titles. I am trying to click on a button next to each title in order to add it to my "currently watching" list. However, my "add" link is not responding to the event handler. What steps can I take to suc ...

Steps for setting up a nickname for individuals within the immediate scope

One snippet of HTML I utilize with ng-include involves a template that is used recursively and requires a scope/controller (apologies, as I am uncertain about the appropriate term in this scenario) named "element": <div> <span>{{element.name}} ...

Encountering a Typescript error while executing an npm script

Upon running tsc && npm run browserify && npm run minify, I encounter the following error: lib/helper.ts:71:38 - error TS4078: Parameter 'inputData' of exported function has or is using private name 'Buffer'. 71 inpu ...

How can I make a DIV occupy the entire vertical space of the page?

I am working on a Google Maps application that takes up the majority of the screen. However, I need to reserve a strip at the top for a menu bar. How can I ensure that the map div fills the remaining vertical space without being pushed past the bottom of ...

I'm looking to configure a backend like node.js/express paired with react using vite. I'm curious about the deployment process - should I rely on vite's commands or node's for this?

(PAY ATTENTION TO THE TITLE) I am new to React and eager to explore Vite.JS. While I have no knowledge of Node.js, I am determined to learn how to connect them. Can you guide me through this process? Also, when it comes to deployment, should I stick to V ...

Passing an ID in Next.js without showing it in the URL

I am looking to transfer the product id from the category page to the product page without showing it in the URL Category.js <h2> <Link href={{ pathname: `/product/car/${title}`, query: { id: Item.id, }, }} as={`/p ...

Increase the time of a Date by 10 seconds

Is there a way to increase the time of a JavaScript date object by 10 seconds? For example: var currentTime = new Date(); var currentSeconds = currentTime.getSeconds() + 10; currentTime.setSeconds(currentTime.getSeconds() + currentSeconds); ...

Issues with Animations in Animate.css

Seeking to achieve fluid transitions using Vue.js and Animate.css, encountering issues with certain animations not functioning as expected! Successfully implementing animations such as: bounceIn, bounceOut, and hinge. Experimenting with this on codepen.i ...

Disable button with Checkbox Javascript functionality

In my PHP code, I have an array of users that I pass to the view (in Laravel) and use a foreach loop to display all users in a table. Everything is working fine so far. However, I want to make a "send" button visible when a checkbox is clicked, instead of ...

Continue the conversation as you scroll down in the chatbox

Struggling to implement an automatic scroll to the bottom of a chat window when a new message appears. HTML: <div class="content chat-body" id="messages"> <div class="chat-message" v-for="message in messages"> <p class="title i ...

Whole page scrolling instead of just inner div scrolling

Once again, I find myself tinkering with CSS... In the current setup, the map container is scrolling on its own, separate from the rest of the content within the container. How can I enable the entire page to scroll when additional content is added to the ...

The SmoothShading feature of THREE does not alter the geometry

I am having trouble with smooth shading on my model - the polygons are still clearly visible and switching between smooth and flat shading in the three.js inspector isn't making a difference. The OBJ file contains vertex normal data, so I don't t ...