Optimizing functions by consolidating them and leveraging shared variables

My index page is quite straightforward - it has buttons that when clicked, randomly change the colors displayed on the background circle divs. The code I've written works well, but it's a bit repetitive; I ended up creating a separate function for each button, and they all look very similar except for the variables they use.

I've been contemplating consolidating these functions into one to avoid redundancy, but I'm struggling to find a way for the clicked button to access the correct variable and alter the background colors accordingly. For instance, take a look at the function for the first button, which uses the colorList variable to change the colors within the gray spectrum:

var colorList1 = [//array of 20 colors]
var colorList2 = [//array of 20 colors]
var colorList3 = [//array of 20 colors]
var colorList4 = [//array of 20 colors]

// .choice-1 represents the div class for the first button
$(".choice-1").on("click", function() {
    blankSlate();
    colorList = colorList1;
    $("[id^='nav']").css("background-color", colorList[1]);
    $("#colorChoice").css("background-color", colorList[1]);
});

I attempted to write some code that would extract the number from the class name and set it as a variable accessible to the primary function, like so:

var buttonVar = $("button").attr[0].nodeValue; // get full name of nodeValue
var btnChoice = buttonVar[buttonVar.length-1]; // access number at end of class name
$("button").on("click",function() {
    $('.choice' + btnChoice).on('click', function(){*/
    blankSlate();
    colorList = colorList + btnChoice;
    $("[id^='nav']").css("background-color", colorList[btnChoice]);
    $("#colorChoice").css("background-color", colorList[btnChoice]);
  });

...but I'm uncertain if this approach is correct, and I'd greatly appreciate advice on how this type of refactoring is typically approached.

If you're interested in seeing my work in action, here's a Codepen link showcasing the functionality along with the HTML, CSS, and the rest of the JavaScript code: http://codepen.io/a6ftcruton/full/Beizu

Answer №1

To enhance the functionality of your clickable elements, consider adding a unique `data` attribute to each element and specify the collection name you desire to access. For easier management, organize your arrays within an object structure:

var myData = {
  list1: [ ... ],
  list2: [ ... ],
  list3: [ ... ]
  // add more collections as needed...
};

Add a common class and the data attribute to your interactive elements:

<a href="#" class="magic" data-collection-name="list2">Tap here</a>
<button class="magic" data-collection-name="list3">Hey there, Click me</button>

Subsequently, listen for events by attaching an event listener like this:

$('.magic').on('click', function () {
  var elem = $(this);
  var chosen_list_name = elem.data('collection-name');
  var desired_data = myData[chosen_list_name];
  // Perform operations with the retrieved data
});

Demonstration available at: http://jsfiddle.net/DFBta/

Answer №2

Looking at the situation mentioned above, it is clear that there is a need for CSS refactoring. I recommend considering one of the options below:

  • PostCSS
  • Stylus

Both of these tools offer features like variables, mixins, functions, and various other techniques to help you create CSS that is easier to maintain, themeable, and extendable.

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

Ensuring radio button validation prior to redirecting to contact form

I created a survey form using HTML and CSS. I am looking to add validation to the questions before redirecting to the Contact form page. Currently, when a user clicks on the submit button in the Survey form, the page redirects to the contact form. Howeve ...

What steps can I take to stop jQuery's $.getJSON function from converting my AJAX response keys into integers?

I am facing an issue where JQuery is changing the type of keys in a JSON response object from text to integer when populating a select box. This causes the response object to be reordered based on the numeric indexes, disrupting the order of the select box ...

Guide to performing a subdomain ajax request using jQuery (minus iFrames)

site.com/api/index.php is where the ajax request needs to go. While it works perfectly from site.com/sub/, it sends the request to sub.site.com/api/index.php from sub.site.com, which obviously does not exist. Despite researching extensively on Google and S ...

The media query for mobile is not functioning properly

Hello, I have a page with MVC that includes CSS for iPad and mobile devices. The media query for iPad (@media only screen and (min-device-width: 768px) and (max-device-width: 1024px)) works perfectly, but I am struggling to get the media query for mobile ...

Generate an image on Canvas using a URL link

I have a unique URL that generates canvas images with specific parameters. It functions properly when loaded in a browser. The final line of code is: window.location = canvas.toDataURL("image/png"); However, when attempting to use this URL from another ...

Why isn't the select filter populating when I use the JQuery DataTable Column Filter plugin?

Currently, I am utilizing the JQuery DataTable Column Filter plugin and encountering an issue where the select dropdown is not being populated. Despite using server-side fetching, I am unsure of how to enable auto-population for the select dropdown. Here i ...

Activating Button/Div on Website Using Python Code

Is it possible to automate asset buying on a trading platform using Python? I have developed an Algorithmic Trader and now want to automatically purchase assets, particularly crypto, at periodic intervals. The exchange I am considering is Phemex. They off ...

The menu bar becomes distorted when the page is zoomed out

Hey everyone, I could really use some assistance with my menus. Whenever I zoom out of the page, they become distorted. Here is the link to my website: https://dl.dropbox.com/u/22813136/Finding%20Nemo%20Inc/FNemo_front.htm# I tested the link on Internet E ...

What is causing my rows to disappear even after I have made them visible?

There is a table with six rows, but initially only two are visible - a header row and one "business" row. A button allows the user to add additional rows one at a time (making existing rows visible), up to a maximum of six rows / five "business" rows. Th ...

The icon for the "Hamburger" menu is missing, but the text is visible

Currently, I am designing the topbar for my website using Foundation. Everything seems to be functioning correctly except for the menu icon not appearing. I have followed the documentation provided by Foundation, but I am still facing difficulties. Here is ...

Unable to get the sublocality dropdown list to cascade properly in asp.net mvc

I am dealing with three dropdown lists. The initial action method for the City dropdown is shown below: public ActionResult Create() { List<SelectListItem> li = new List<SelectListItem>(); li.Add(new Sel ...

Create a responsive design for a webpage that adjusts font size based on the dynamic type settings in iOS

Is there a way to ensure that my website's font size dynamically adjusts for iOS users? For example, if a user changes the font size in their iPhone settings (Settings > General > Accessibility > Larger Text), I want the webpage font size to ...

Using HTML and JavaScript, we can set two different color values - one for the background and one for the h1 title

I am trying to save two values, one for the h1 tag and one for the body background. I want the user to select color 1 and color 2. When I press the third button, all changes should be applied and the colors should change. I have attempted this but with no ...

"Enhance Your WordPress Website by Filtering Posts Dynamically with

I stumbled upon this awesome tutorial about filtering WordPress posts by category with AJAX on Pixelers.net: and it's been really helpful. Now, I am looking to create a filter for popular and recent posts. The popular post should be based on the num ...

Retrieve the response text from a jQuery.get() call and return it

Attempting to achieve the following: var msg = $.get("my_script.php"); Expecting msg to be assigned to the text returned by my_script.php, which should be the responseText of the jqXHR object. However, it seems that msg is consistently set to "[object XM ...

Issues with VS Code detecting inline JavaScript variables in an HTML file when referenced in a TypeScript file

In my index.html file, there is an inline script containing various variables... <body> <div id="load-form-here"></div> <script> let formID="abc123" let myBool = true let myArray = ["foo" ...

Tips on how to automatically rearrange a jQuery UI sortable list

Currently, I am working with 2 jQuery UI sortable lists which can be found at http://jqueryui.com/demos/sortable/#connect-lists. The process involves dragging items from list A (catalog) to list B (basket). I have a specific requirement where I need the ...

Modifying the color of the tooltip arrow in Bootstrap 4: A step-by-step guide

How can I change the arrow color of the tooltip using Bootstrap 4? Here is my current code: HTML: <div class="tooltip-main" data-toggle="tooltip" data-placement="top" data-original-title="Service fee helps Driveoo run the platform and provide dedicate ...

Choosing the order of a list with jquery: a simple guide

Hello everyone, I am currently working on implementing a feature where my webpage slides left or right based on which menu item is clicked. Each menu item has a list order value assigned to it. Here is how I envision it happening: When a user clicks on a ...

Adjust the IFRAME height to 100% scaling

I am having trouble setting the height of my iframe to 100%. Despite my efforts, I can't seem to make it work properly. What I really want is for the iframe to display without any scroll bars every time and have a height of 100%. See below for the co ...