Tips for maximizing efficiency and minimizing the use of switch conditions in JavaScript when multiple function calls are needed

After coming up with this code a few minutes ago, I began to ponder if there was a more elegant way to optimize it and condense it into fewer lines. It would be even better if we could find a solution that eliminates the need for the switch condition altogether.

        switch(orientation){
            case 'l':
                $('landscapeButton').addClassName('active');
                $('portraitButton').removeClassName('active');
                break;
            default:
                $('landscapeButton').removeClassName('active');
                $('portraitButton').addClassName('active');
        }

Do you think it's possible to further optimize this code? If so, how would you go about achieving that?

Edit: I forgot to mention which library/libraries I am using. I typically use both Prototype and jQuery, but for this example, I went with Prototype as it's my preferred option for handling CSS class names. Regardless, I'm open to solutions in either Prototype or jQuery. Thank you to everyone!

Answer №1

To utilize prototypejs:

If the value of orientation is either 1 or 0, a function can be used with a switch argument to toggle appropriately.

function adjustClass(id, className, switch) {
    return $(id)[(!!switch ? "add" : "remove") + "ClassName"](className);
}

adjustClass('landscapeButton', 'active', +orientation);
adjustClass('portraitButton', 'active', !+orientation);

For jQuery users:

In jQuery, this functionality is built into their method called toggleClass.

$('#landscapeButton').toggleClass('active', +orientation);
$('#portraitButton').toggleClass('active', !+orientation);

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 to use jQuery to update a text input field based on a selected <select> dropdown option

Hi there, I could really use some help with this issue... Here's the problem - I need to change the value of a textbox within a table based on the selection of an option in a dropdown. Here's a simplified version of what I mean: <select id= ...

Tips for creating a responsive carousel slider for images

No matter how much I've tried, I can't seem to find a solution on how to make my image responsive along with the caption. Below is my HTML code: <section id="banner"> <div class="banner-bg"> <div class="banner-bg-item ...

How to dynamically update data in Angular without the need for a page refresh or loading?

Looking to enhance a wishlist feature by enabling users to delete items from the list without the need for a page refresh. Here's my approach: wish.controller('wishCtrl',['$scope','$http','$cookies','$wind ...

The struggles of using a jQuery tree with JSON data are real, especially when it comes to dealing with the

I am in the process of creating a tree structure from JSON data that is dynamically loaded from PHP files. However, I am facing difficulty in navigating to the third level of the tree. Below is the code snippet: $(document).ready(function() ...

Having trouble with Ajax.updater?

I am a JavaScript newcomer and currently facing an issue with prototypes. I am attempting to update sample.jsp using Ajax.updater after it is loaded, but for some reason, it's not working. Here is the source code of sample.jsp: <%@page contentTyp ...

Utilizing the fs module in Node.js

Hello friends! Currently I am faced with an issue while trying to import the fs module in nodejs. Initially, I utilized require to import it like so: const fs = require('fs'); Everything was functioning smoothly until recently when it suddenly ...

What is the technique to transfer the value from collection_select to the onchange method in Rails?

In my task, I need to extract the selected value from the collection_select drop-down menu and pass it to an onchange function. However, when I access the "name" attribute, the printed value is source[index]. Instead, I want to retrieve the actual value ...

Is it possible that the method of wrapping options using an array is not functioning correctly in the quiz app being managed in React?

I need your help in figuring out where I've made a mistake. The following line is causing an error: const choices = Array.forms(document.querySelectorAll('.choice')); console.log(choices); ...

include a button next to the input field

As you reduce the browser window size, you may notice a different layout designed specifically for iPhone. One question that arises is how to add a button next to the search text box dynamically using JavaScript. The issue at hand is that the text box is b ...

Tips for uploading numerous images to Firebase using React Native Fetch Blob

I have a collection of images stored in an array (image paths are stored in the array). I am trying to upload each image using a for loop, but only the last image gets uploaded. My approach involves using React Native Fetch Blob and Firebase for this task. ...

When I request the value of a JavaScript object, I am met with 'undefined'

I have been working on creating a Google map application that involves loading markers from a database and displaying them on a map. To accomplish this, I decided to create an array and define an object as shown below: function shop_info(name, latitude, l ...

Executing a controller function in AngularJS from an event

I am facing an issue with my AngularJS code. I have defined a function within my controller, and I am trying to call it inside an event listener, but I keep getting an 'undefined' error. Here is how the controller code looks like: inputApp.cont ...

Issue: jQuery's parseInt() function consistently results in NaNExplanation:

I have created a simple function that adds a new row to a table, and this function is working well. However, I am encountering an issue with the parseInt() part of the code. The first row in the table includes an ID, which triggers the if-clause correctly ...

Automatically unset session variable 'unsetted' using a simple line of code

Why does the session information not get saved? When I reload the page, the session variable 'mucciusersess' disappears. What could be causing this issue? Thanks... I have a cookie on the client-side with a value like 'mucciuserid' se ...

Exploring the world of React-Bootstrap elements and properties

I'm currently diving into a Bootstrap home project and it's my first time working with Bootstrap. I came across a tag that has an 'inverse' attribute among others like 'fixedTop', 'fluid', and 'collapseOnSelect& ...

Leveraging the power of React Native with embedded RapidAPI functionality in the source

I had previously used the following code to retrieve a JSON file containing personal data in my React Native source code: async componentDidMount() { try { const response = await fetch('mydomain.org/personaldata.json'); const responseJson ...

What is the best way to dynamically insert columns into HTML code?

This is an example of my HTML code: <div class="row text-center"> <div class="col h4">We Collaborate With:</div> <div class="col">company1</div> <div class="col">company2</div> ...

Adjust a Javascript script to choose the best font color for use in R Shiny applications

I am currently seeking to determine the font color of hover messages based on the background color. This means white if the background is dark, and black if it is light. However, I stumbled upon a Stack Overflow question with a Javascript solution that see ...

Click on the child element while it is already being clicked by manually implementing the 'declick' function in Javascript

Hey there, I'm looking for suggestions on a better title for this issue. I couldn't come up with the right wording myself. Problem I currently have a Google Maps element with pointer events set to none, preventing it from being scrolled when ho ...

Is it possible to eliminate the arrows from an input type while restricting the change to a specific component?

Is there a way to remove the arrows from my input field while still applying it only to the text fields within this component? <v-text-field class="inputPrice" type="number" v-model="$data._value" @change="send ...