What is the best way to construct a jQuery function that contains several .click() events?

What is the best strategy for creating this function that I am working on?

my_script.js

$(document).ready(function() {


     $("#home").click(function() {
         $('.banner').animate({top:'370px', height:'250px', }, 1000)
         return false    
     })

     $("#about").click(function() {
         $('.banner').animate({top:'20px', height:'145px', }, 1000)
         return false
     })


     $("#games").click(function() {
         $('.banner').animate({top:'20px', height:'145px', }, 1000)
         return false
     })

     $("#district").click(function() {
         $('.banner').animate({top:'20px', height:'145px', }, 1000)
         return false
     })

     $("#contact").click(function() {
         $('.banner').animate({top:'20px', height:'145px', }, 1000)
         return false
     })


})

If an id in ["about","contact","district", "games", "membership"] is clicked, I want to trigger some animations. However, if id = "home" is clicked, I want to animate it back (or keep it stationary if already on that page).

The code provided above does not work as intended. What approach would you recommend? Should I store the IDs for the banner animation positions in an array and loop through them? How would that implementation look? Alternatively, should I create separate functions for each ID, like I have done currently?

/W

Answer №1

It is recommended to assign a shared class instead of using individual ids, with the exception of the home item, since the code is the same for all items other than home.

$("#home").click(function() {
    $('.banner').animate({top:'370px', height:'250px', }, 1000)
     return false;    
});

$(".sharedclassexceptforhome").click(function() {
     $('.banner').animate({top:'370px', height:'250px', }, 1000)
     return false;    
});

Answer №2

Here is a way you could attempt it:

$("#home").click(function() {
     $('.banner').animate({top:'370px', height:'250px', }, 1000)
     return false;    
 });

 $("#about,#contact,#games,#district").click(function() {
     $('.banner').animate({top:'20px', height:'145px', }, 1000)
     return false;
 });

Answer №3

Creating a function with specific parameters allows for simplified handling of click events. Simply call the function when clicking and provide the necessary parameters for positioning.

Answer №4

This is a revised version of the code you were previously viewing. The requirement was to prevent animation on the element with class "banner" if it is already active (is this condition only for the home page?). Therefore, the function will now return false if the clicked item has the class "active".

It should be noted that I have not tested the code as I do not possess the remaining portions of the code.

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

Proper method for retrieving Scroll Position

Within my application, I am aiming to identify the current scroll position. To achieve this, I have been utilizing the following method (reference: ) window.pageYOffset || document.documentElement.scrollTop Dilemma: Upon logging this information, it consi ...

Guide on implementing page styles to a polymer element

To apply styles from a 'normal' stylesheet to my polymer component, I included shim-shadowdom in the style and added /deep/ to the class. Here is an example: <html> <head> <style shim-shadowdom> .mylink /deep/ {col ...

Choosing the Iframe amongst various other tags in Selenium

Hey there! Let me give you a quick summary: I'm facing a challenge of selecting an element within an iframe that is nested inside several other HTML tags. Here's the issue at hand: Today, I'm tackling a task at work that involves filling ...

How can I adjust the height of a div to fit between a fixed navbar at the top and a pinned footer at the bottom?

I am facing a challenge with a div containing a Bing map that needs to stretch to fill the entire height of the page. While I have successfully used container-fluid for the width, adjusting the height is proving tricky due to the fixed heights of the navba ...

Hide Address with Jquery Dialog Box

How can I securely redirect a user to another page within the same website? In my specific situation, I have a form where users input information. For cancellations, they should have options available. When a user clicks the cancellation button, a dialog ...

Tips for resolving rendering page issues in an express app

My application is a straightforward blog platform that showcases a schema for the title, entry, and date of each blog post. There is also an edit/delete feature that is currently under development. When attempting to use the edit/delete button on a selecte ...

Error encountered due to unidentified JSX syntax within div element

**** When I check the terminal, this is what I see **** ./src/card.js Line 9:9: Parsing error: Unterminated JSX contents 7 | <h2>john doe</h2> 8 | <p><a href="/cdn-cgi/l/email-protection" cl ...

JavaScript - memory heap exhausted

Recently, I encountered an issue with my API written in Node.js. The purpose of this API is to read data from a MySQL database, write it into a CSV file, and allow users to download the file once the writing process is complete. Initially, everything was f ...

How can Three.js help you identify whether a point lies on a given line?

Is there a way to determine if a specific point (x,y,z) lies on the line segment between two other points, pointA and pointB? I am looking for a boolean function that can efficiently solve this problem: pointA // random THREE.Vector3 pointB ...

Tips for changing the first letter to uppercase in a p5.js variable

I'm currently working on developing a weather forecasting website using the p5.js framework in JavaScript. One issue I am facing is that the API I am utilizing only provides weather descriptions in lowercase format, whereas I want them to be displayed ...

Tips for preserving an HTML dynamic table in a database

I have a challenge where I am generating a dynamic HTML table using javascript. What is the best way to store this dynamic HTML table in a database using CodeIgniter? This is the code snippet for my input form: <table id="tb3" name="tb3"> & ...

Exploring the controller logic in Sails.js index.ejs

I'm struggling to understand how to integrate dynamic logic into the homepage of my Sails.js application. Currently, the homepage is static, but I want to display data on the index.ejs page. I have a MainController with an index function that retrieve ...

Learn to save Canvas graphics as an image file with the powerful combination of fabric.js and React

I am currently utilizing fabric.js in a React application. I encountered an issue while attempting to export the entire canvas as an image, outlined below: The canvas resets after clicking the export button. When zoomed or panned, I am unable to export co ...

Extract data from JSON object on the server side

Within my web service, I have a method that returns a JSON object: {name:'xx'} When making an Ajax request and parsing the response with 'eval', I encountered an issue. onComplete:function(req){ var data=eval(req.responseText); / ...

Is there a way to prevent links from opening in an iframe and have them open in the main window instead?

Imagine you have an iframe on your webpage: <iframe style="border-radius:15px;" width="190" height="450" frameborder="0" scrolling="no" marginheight="5" marginwidth="10" src="../img/interactive_map/interactive_sverige.htm"> </iframe> ...

When webpack DllPlugin is utilized alongside bootstrap 4 beta, it leads to an Uncaught ReferenceError

Currently, I am utilizing DllPlugin in my development environment. However, once I introduce bootstrap into the build, it causes my vendor dll to break. Interestingly, if I comment out bootstrap, all other references work perfectly fine. Below is the relev ...

Creating a file of a specific size using Node.JS WriteFile

Are there any techniques to designate the size or length of a file and ensure that the system allocates the necessary space? I am interested in something along the lines of: fs.write('file', Buffer, 1024*1024*54); // To generate a 54MB file. ...

I am looking for a way to showcase the form value either in the address bar or transfer it to another page using JavaScript. Can

Currently facing a challenge with a form where I need to input the name and email, redirect these values to another page, and display them in the address bar using only JavaScript. Take a look at the form here: View Form Code snippet for the form: <f ...

What could be causing my jQuery generated dropdown to not update with the selected value?

It seems like I must be overlooking a simple detail, but for the life of me, I can't figure it out. In my ASP.NET MVC application, I have a situation where a dropdown is being generated dynamically based on the selection of another dropdown. The dropd ...

When the Next js page loads, it briefly displays a 0 at the top for a moment before loading the rest

When my nextjs app loads a page, there is a momentary appearance of a 0 in the top left corner. This happens even if I am fetching data from Sanity CMS using getStaticProps and returning content. Interestingly, I have observed that simply returning an empt ...