Is transforming lengthy code into a function the way to go?

I have successfully implemented this code on my page without any errors, but I am wondering if there is a more concise way to achieve the same result. Currently, there is a lot of repeated code with only minor changes in class names. Is it possible to shorten this code by using a function or loop? Your suggestions would be greatly appreciated.

//menu
            $('.aboutOne').click(function(){
                $.scrollTo('.basicsRow', 1000, {axis:'yx'});
                $.scrollTo('.basicsRow', 1000, {axis:'xy'});
            })
            $('.aboutTwo').click(function(){
                $.scrollTo('.storyRow', 1000, {axis:'yx'});
                $.scrollTo('.storyRow', 1000, {axis:'xy'});
            })
            $('.aboutThree').click(function(){
                $.scrollTo('.teamRow', 1000, {axis:'yx'});
                $.scrollTo('.teamRow', 1000, {axis:'xy'});
            })

            // Code repeats above sequence...

Answer №1

To enhance manageability, consider consolidating everything into an object and then passing it to a function:

var elements = {
     '.aboutTwo':'.teamRow',
     '.aboutThree':'.homeRow',
     ...
};

function handleMenuClick(elements){
     $.each(elements, function(key, value){
         $(key).click(function(){
            $.scrollTo(value, 1000, {axis: "yx"});
            $.scrollTo(value, 1000, {axis: "yx"});
         });
     });
}

// Invoke the function
handleMenuClick(elements);

This approach allows for easy modifications by simply updating the elements object.

NOTE: It is recommended to use jQuery's .on() method (Documentation) for event binding.

Answer №2

To specify the scrolling destination for each clickable element, I suggest utilizing data- attributes like this:

 <a class="clicktoscroll sectionOne" data-target="introSection">...</a>

You can simplify your code by using just one event handler:

        $('.clicktoscroll').click(function(){
            var $target = $(this).data('target');
            $.scrollTo('.' + $target, 1000, {axis:'yx'});
            $.scrollTo('.' + $target, 1000, {axis:'xy'});
        })

Answer №3

To enable smooth scrolling on your website, consider utilizing a custom data-* attribute such as data-scroll-to. This way, your elements can dictate where the page should scroll to.

<button class="about" data-scroll-to=".basicsRow">Button</button>

Here is an example implementation:

$("[data-scroll-to]").each(function() {
    var $this = $(this), target = $this.data("scroll-to");
    $this.click(function() {
        $.scrollTo(target, 1000, { axis: 'yx' });
        $.scrollTo(target, 1000, { axis: 'xy' });
    });
});

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

Ways to acquire the reference of the parent component

Within my code, there is a parent component represented as: <Parent> <Child (click)=doSomething()></Child> </Parent> I am looking to establish a reference to the Parent component in order to pass it within a method that will trigg ...

extract keys and values from an array of objects

I would like assistance with removing any objects where the inspectionScheduleQuestionId is null using JS. How can we achieve this? Thank you. #data const data = [ { "id": 0, "inspectionScheduleQuestionId": 1, ...

What is the best way to align two divs next to each other while keeping the second one centered with flexbox?

Here are my two div elements: <div class='container'> <div class='left'></div> <div class='centered'></div> </div> I am looking to center the second inner div and have the first inner ...

Ensure that the date range picker consistently shows dates in a sequential order

Currently utilizing the vuetify date range picker component https://i.stack.imgur.com/s5s19.png At this moment, it is showcasing https://i.stack.imgur.com/GgTgP.png I am looking to enforce a specific display format, always showing the lesser date first ...

The content of the string within the .ts file sourced from an external JSON document

I'm feeling a bit disoriented about this topic. Is it feasible to insert a string from an external JSON file into the .ts file? I aim to display the URLs of each item in an IONIC InAppBrowser. For this reason, I intend to generate a variable with a sp ...

What is the right rendering strategy to use for shouldComponentUpdate in React?

Provide an exhaustive list of all props required for rendering shouldComponentUpdate(nextProps, nextState) { if (this.props.color !== nextProps.color) { return true; } if (this.state.count !== nextState.count) { return true; ...

Discovering how to efficiently track and respond to changes in MobX state within a React

Within my react native project, I have observed that upon clicking a button, the state of my mobx app undergoes an update. To address this issue, I aim to employ a react lifecycle method that can monitor and automatically reflect this modification. For th ...

Troubleshooting Google Web Fonts

I seem to be using code similar to what I used before, but it appears that the fonts are not loading. <html> <head> <script src="http://fonts.googleapis.com/css?family=Yanone+Kaffeesatz:extralight,light,regular,bold"></s ...

The class name remains unchanged despite the change in value

I am currently working on a webpage that features two interactive tabs. The goal is to have one tab highlighted as "active" while the other remains inactive when clicked, and then switch roles when the other tab is selected. Below is the code snippet I ha ...

What is the best way to showcase a ul element as inline-block?

Is there a way to keep the bottom menu aligned in one row on all screen sizes? I attempted using display: inline-block, but it doesn't seem to work for me. Below is the CSS code: footer #middle-footer { background: #F6F6F6; color: #000; font-size ...

Click on a specific image in a table using Cypress with a specific source URL

I need help with a query for Cypress regarding a table of items, each item having active (blue) and not active (black) images. How can I set up this query? Below is an image of the table list: https://i.stack.imgur.com/74qzb.png And here is the HTML code ...

Designing links within a web application

Currently, I am developing a web application that will contain a high volume of clickable elements. The challenge lies in maintaining a visually appealing design while adhering to web best practices such as using different colors and underlines for links. ...

What techniques can I use to achieve a seamless transition using Javascript and CSS?

I'm striving for a seamless CSS transition. The concept of transition had me puzzled. Even though I utilized the setTimeout method in JavaScript to make my CSS functional, it lacks that SMOOTH feel! Check out my code below. function slideChange( ...

Instructions on how to modify a document's content by its unique identifier using Firebase Modular SDK (V9)

I am trying to figure out how to update an existing document for the same user ID in V9 Firebase whenever they log in, rather than creating a new one each time. Any suggestions on how to achieve this? Current Code setDoc( query(collectionRef), // ...

Checking for mobile SSR in a ReactJS applicationUncover the signs of mobile

I recently integrated the mobile-detect library into my project following this informative tutorial: link /src/utiles/isMobile.tsx: import MobileDetect from "mobile-detect"; import { GetServerSidePropsContext } from "next"; export co ...

Issue with Object.keys printing in an abnormal manner

My goal is to extract only the keys from an object, but instead of getting the desired output with the keys, I am seeing numbers. Here is the code snippet: data = {"property" : "{\"animalID\": \"12345\" ...

the reason behind the peculiar behavior of angularjs ng-include

I am attempting to utilize an ng-template to iterate through my args in order to create an indented menu content. Unfortunately, I have encountered issues with ng-include not working as expected. I have tried adding a quote but it still does not work. For ...

Are there any performance implications when using an excessive number of background images in CSS?

My website seems to be running too slowly based on user reports. I suspect that the background images in CSS may be causing the issue. The site uses a custom build system to concatenate and compress all CSS, create CSS sprites automatically, resulting in ...

Tips for incorporating inline styling into the body element

Can someone help me with adding inline style to the body element using jQuery? I want to set the background color to white (#FFFFFF). Your assistance would be highly appreciated. Thank you! ...

Retrieving Data from Outside Source using AngularJS

Is there a way to retrieve JSON-Text-Stream data from a specific URL (e.g. SOMEURL/ean.php?id=4001513007704)? The returned result typically appears as follows: { "product": { "ean_id": "4001513007704", "title": "Gerolsteiner Mineralw ...