Which shortcuts or techniques in jQuery/JavaScript can I implement to simplify this code further?

I've written a script to handle responsive design for smaller devices and display a toggle menu instead of a full-width menu. The current script works, but I find it messy. How can I make this code more minimalistic and efficient?

Is it good practice to use the resetMenu() function to maintain CSS for specific resolutions when resizing the browser from normal to toggle mode?

$(document).ready(function($) {
function resetMenu() {
    $('#top-menu li, #search-form, .social').css({"display":"block"});
    $('#top-menu li').css({"display":"inline-block"});
};
$(window).resize(function () { 
if($(window).width() > 640){
    $(resetMenu());
}
else{
    $('#top-menu li, #search-form, .social').css({"display":"none"}).fadeOut(1000);
    $('#top-menu li:nth-child(2)').css({"display":"none"});
}
});

$(".togglebutton").toggle(
function () {
    if($(window).height() < 360){
        $('#top-menu li').css({"display":"inline-block"}).fadeIn(500);
        $('#top-menu li:nth-child(2)').css({"display":"none"});
        $('#search-form, .social').css({"display":"block"}).fadeIn(500);
        $('#top-menu li').css({"border":"none"});
    }
    else{
        $('#top-menu li, #search-form, .social').css({"display":"block"}).fadeIn(1000);
        $('#top-menu li:nth-child(2)').css({"display":"none"});
    }
},
function () {
    $('#top-menu li, #search-form, .social').css({"display":"none"}).fadeOut(1000);
    $('#top-menu li:nth-child(2)').css({"display":"none"});
}

)});

Answer №1

When it comes to coding, I have a preference for separating declaration and execution parts into different modules. For example:

var one = $('#top-menu li')
var two = $('#top-menu li, #search-form, .social');
var three = $('#top-menu li:nth-child(2)');
var four = $('#search-form, .social')

function toggleIn() {
    if($(window).height() < 360){
        one.css({"display":"inline-block"}).fadeIn(500);
        three.css({"display":"none"});
        four.css({"display":"block"}).fadeIn(500);
        one.css({"border":"none"});
    }
    else{
        two.css({"display":"block"}).fadeIn(1000);
        three.css({"display":"none"});
    }
},

function toggleOut() {
    two.css({"display":"none"}).fadeOut(1000);
    three.css({"display":"none"});
}

function resetMenu() {
    one.css({"display":"block"});
    two.css({"display":"inline-block"});
};

On the other hand, a more minimalistic approach could simply be:

$(window).resize(function () { 
    if($(window).width() > 640){
        $(resetMenu());
    }
    else{
        two.css({"display":"none"}).fadeOut(1000);
        three.css({"display":"none"});
    }
});

 $(".togglebutton").toggle(toggleIn, toggleOut);

This allows for easier evaluation of each functional part of the code, making it useful for debugging purposes.

Answer №2

Your code may not seem messy to everyone, but there are ways to improve its organization. Consider defining and naming your anonymous functions outside of the event handlers and passing them in as parameters. Creating an object like WindowTracker to manage window properties and moving response functions into it can help implement builder and observer patterns for more modular and separated code. Storing the results of jquery searches internally for function calls can also optimize efficiency. Here's a helpful resource on saving jquery selectors for later use.

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

Bootstrap - the input group button is designed to align to the right side

Currently, I am in the process of constructing a navigation bar for a website that includes a search bar and a grouped button. Everything functions properly when viewed on a desktop, but as soon as I switch to mobile view and the collapsible menu is activa ...

Preview and crop your image before uploading

Currently, I am working on developing a form that will enable administrators to upload an image. The aim is to allow them to preview the image before uploading it, displaying it at a specific size and providing the option to click on the image to open an i ...

Fill in according to the options selected in the dropdown menu

Recently delving into the world of React, I encountered a design challenge that needs solving. My goal is to have a selection field with various choice values, each offering different sets of KPIs and UOMs. Depending on the chosen value, I should be able t ...

The functions within the document.ready() function do not execute following an AJAX request

Running a Drupal commerce website with dynamic drop down menus that fetch products from the database in real time using Ajax. The issue arises when changes are made to these menus, causing the functions within my document.ready() to cease working. Attempt ...

Steps for displaying an image link on an aspx webpage

Is it possible to have the full-size image open on http//example.com/image.aspx when the thumbnail is clicked, instead of http//example.com/images/image.jpeg? I am looking for a solution that does not require creating individual pages for each image or edi ...

Can the browser tabs automatically detect when a user logs out?

When I have multiple tabs open of the same website in a browser, I wonder how other windows can detect when a user has logged out. My development setup involves using Python/Django. The method I am currently implementing is: function user_checking(){ ...

Is it possible to insert a button into a specific column of an ngx-datatable within an Angular 8 application?

I am having trouble with this particular HTML code. <ngx-datatable-column name="Option" prop="option" [draggable]="false" [resizeable]="false [width]="250"> <span> <button class="optionButton" type="button" data-to ...

Increasing Taxes and Boosting the Overall Cost

How can we set up a system where taxes are bypassed by default unless otherwise specified when placing an order? Let's take a look at the following text box: <input class="txt1" type="text" name="subtotal" value="" id="subtotal" size="16" ta ...

Creating a Javascript function to turn lights off using CSS manipulation, similar to the feature found

Is there a way to use JavaScript to obscure all elements on a page except for one specific HTML element? This web application is optimized for Chrome, so CSS3 can also be utilized. ...

Having trouble retrieving multiple selected values from the paper listbox in Polymer 3

I'm attempting to retrieve multiple selected values in a paper-listbox element in Polymer. <paper-dropdown-menu label="{{_getLabel('Activity Type')}}" id="fromMenu" on-paper-dropdown-close="fromAccountChanged" searchable="true"> ...

Customizing Django forms.Textarea in template or declaring in models is essential for creating a unique

Within my models, I have a forms.Form that includes a textarea field: answer1 = forms.CharField(label='Answer 1', widget=forms.Textarea(attrs={"placeholder":"Type your answer...", "rows":6, "cols":45}), max_length=150) When it comes to views: ...

When attempting to run JavaScript within PHP, an Uncaught SyntaxError is encountered

When I run this code without PHP, it works perfectly. <?php $activeStatus = "$getuser[active]"; if($activeStatus == 1) { echo '<script type="text/javascript">'; echo ' $(document).ready(function () { v ...

Enable the script tag with the type "module" only under certain conditions

Attempting to dynamically enable script tags in HTML using the code below does not yield the expected results. function loadScript() { document.querySelectorAll('script[type="text/skip-hydration"]').forEach((script) => { script ...

Exploring the world of mocking and stubbing in protractor

I am interested in testing my angular application using protractor. The app includes an API Module that communicates with the server In these tests, I would like to mock this API Module. I am not looking to perform full integration tests, but rather tests ...

What is causing me to receive a Request Method of "GET" instead of "POST"?

I recently implemented the dropzone js library for uploading images and have a query regarding it. Is the POST method more suitable than GET when uploading an image? If yes, how can I rectify this? $(document).ready(function() { var myDropzone = new Dr ...

React Native / Redux - The "Cannot update during an existing state transition" error occurs when attempting to update

Currently working on an app using React Native and Redux, I've encountered a snag in the implementation process. An error message pops up saying setState cannot update during an existing state transition (such as within render or another componen ...

Is there a way to arrange the outcomes in a single line?

I need help displaying my results in three rows side by side in React/JavaScript using flexbox. Since I only have one CardItem, I can't just copy and paste it three times as it would show the same result in each row. Is there a way to achieve this wit ...

How to target the following element with CSS that has a specified class name

Would it be possible to achieve this using CSS alone, or would I need to resort to jQuery? This is how my code currently looks: <tr>...</tr> <tr>...</tr> <tr>...</tr> <tr class="some-class">...</tr> // My g ...

What criteria does Angular use to determine when the aot compiler should be utilized?

This page discusses the concept of modules in Angular and explains the two approaches to bootstrapping - dynamic and static. The configuration for these approaches is typically found in main.ts: // Using the browser platform with a compiler import { platf ...

Continuously make Ajax requests to populate numerous div elements

There are two div elements present on my webpage. <div id="1"></div> <div id="2"></div> I am attempting to dynamically populate these divs using the following php call. <script> var queries = ["SELECT * from table1", "S ...