Revamping repetitive JavaScript code for the pagination of Instagram Stories

I'm currently developing a website that utilizes fullpage.js and includes a section with multiple slides. These slides automatically transition every 10 seconds.

I wanted to implement progress bars similar to those on Instagram, where each bar fills up gradually. When one bar is filled, the viewport switches to the next slide and the next bar begins filling up. Additionally, when a user manually navigates between slides, the corresponding bar should start animating.

After not finding any suitable solutions online, I decided to build it from scratch. Although I eventually got it working as intended, the code turned out to be quite messy.

I am confident there must be a more concise way to achieve this functionality, but my current skill level doesn't allow me to refactor the code effectively. I would greatly appreciate any assistance in optimizing this function with less code to aid in my learning process.

Below is the relevant code snippet I've written (please note that it may not function properly due to being based on the URL, but you should be able to grasp how it would work with the correct URL).

function locationHashChanged() {
  if (location.hash === '#page2') {
   document.getElementById("Loadingbar-2-1").setAttribute("style","animation-name:loadingbar;animation-duration:10s;animation-timing-function:linear;");
   document.getElementById("Loadingbar-2-2").setAttribute("style","width:0%");
   document.getElementById("Loadingbar-2-3").setAttribute("style","width:0%");
   document.getElementById("Loadingbar-2-4").setAttribute("style","width:0%");
   document.getElementById("Loadingbar-2-5").setAttribute("style","width:0%");
   document.getElementById("Loadingbar-2-6").setAttribute("style","width:0%");
  } else if (location.hash === '#page2/1') {
   // Update styles accordingly
  }
  // Add additional condition checks here
  
}  

window.onload = locationHashChanged;
window.onhashchange = locationHashChanged;

Answer №1

If you're looking to streamline the code (even though verbosity can sometimes be beneficial), consider this alternative approach:

const animationStr = "animation-name:loadingbar;animation-duration:10s;animation-timing-function:linear;";
const barsCnt = 6;

function checkHashChange() {
  const num = location.hash.match(/^#page2(?:\/(\d))?$/)[1] || 0;
  
  for (let i = 0; i < barsCnt; i++) {
    const style = i < num
      ? "width:100%"
      : i > num
      ? "width:0%"
      : animationStr;
    
    document.getElementById("Loadingbar-2-" + (i + 1)).setAttribute("style", style);
  }
}

window.onload = checkHashChange;
window.onhashchange = checkHashChange;

I've run some tests on this version, but it could still have room for improvement. Please review and verify.

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

Aligning content within a div block

I created a div block that houses a form structured like this: <div class="divClass"> <form id="frm" method="post" action="/NotDefinedYet/index.xhtml" class="frmClass"> <input type="text" name="j_idt9:j_idt10:Username" placehold ...

The code for implementing the "Read More" feature is not functioning as intended

I have been experiencing an issue with the implementation of the "read more" feature on my website. Although the code seems to be functioning properly, it only works after pressing the read more button twice. This particular code is designed to detect the ...

What is causing the malfunction with this JQuery/AJAX request?

Currently in the process of setting up an autocomplete feature. Following the guidance from php academy at the moment. My goal is to display "suggestions go here" below the input field whenever something is typed in. I have two files for this task: home.ph ...

Live PHP statement continuously updates display

Below is the setup for my input field. The question to fill in the input will only be prompted if either $client_chargeBy is equal to "Square Foot" or "Room" <div class="col-md-12 p0 "> <div class="col-md-6 PL0 p0_smresp"> <di ...

What is the best way to verify the presence of a value in an SQL column?

I need to check if a value exists in a column. If the value already exists, I do not want to insert it into the table. However, if it does not exist, then I want to add new data. Unfortunately, my attempted solution hasn't been successful. You can fi ...

Elements that are hidden or not displayed are still able to receive mouse over events

I am in the process of learning how to handle events within svgs and I have encountered a strange issue. Currently, I am working on an infovis project where I create an interface to display various column-graphs. This part is functioning well so far. Ho ...

Mongoose parameters do not accept passing an id or element

When working with MongoDB and using mongoose, I attempted to remove an item from a collection by utilizing the findByIdAndDelete() method. However, I encountered the following error: CastError: Cast to ObjectId failed for value "5f080dd69af4c61774ef447f" a ...

What is the layout of JqueryMobile web pages like?

When I need to pull pages, I use Asp.net MVC. The format of my pages is as follows: { Layout = ""; } <div data-role="page"> .... <script type="text/javascript"> $(document).one("pageinit", function () { . ...

Using the dot operator to load an image

Is it possible to using the dot operator to load an image? Let's talk about this as a sample image URL <img src={{GET_PROFILE_DATA.googleProfileData.fullName}} alt="profile" class="home-screen-profile-image"> Take note of the unusual looking ...

What could be the reason for Firefox cutting off circular PNG images at the bottom?

Can you explain why Firefox is cutting off circular png images at the bottom of this page: It's strange that IE 10 and Chrome don't have this issue with cropping the images. ...

The 'load()' event method in jQuery does not function properly within the 'ready()' event method on mobile browsers

After testing on Firefox mobile and Chrome mobile browsers, I found that my code works perfectly on computer browsers. Below is the code I have inside the ready() and load() event methods: $(document).ready(function(){ $(window).on('load hashchan ...

The Redux state fails to start with the default initial state

I'm a newcomer to react-redux. In my reducer, I have the following structure: const initialState = { Low: [ { id: 0, technologyId: 0, technology: '', type: '', ...

CSS code that fixes a textarea at the bottom of a div

I need help placing a textarea at the bottom of a fixed div: <div id=msg> <div id=content> aaaaaaaannnnnnnnnn<br> aaaaaaaannnnnnnnnn<br> aaaaaaaannnnnnnnnn<br> </div> <div id=text> <textar ...

Creating a hover effect in CSS that applies to neighboring elements with similar attributes

My table is created using a struts2 iterator and has variable length and content. It looks something like this: <table> <tr class="odd" machineId="1" parameterId="1"><td></td></tr> <tr class="even" machineId="1" pa ...

The Angular translation function is being called repeatedly without end

I have a function that performs text translation. It is hooked to all the text elements and appears as follows: $rootScope.translateText = function (key) { if (angular.isDefined(Language.dictionary[key])) { return Language.dictionary[key]; } ret ...

Using data-image as the source for Bootstrap Modal

I am currently working on an image gallery that utilizes the Paver jQuery plugin. The gallery is functional, but I am facing an issue where it displays the same image in the modal instead of showing the respective data-image for each image. My goal is to ...

The background color is not displaying correctly on the <div> element

body { background-color: #FFFDEC; } .header { position: fixed; top: 0; left: 0; height: 50px; width: 100%; background-color: #04A7A6; margin: 0; display: block; z-index: 10; } .headermenu { xposition: fixed; ...

Customizing ExtJS 4's CSS reset specifically for tailored HTML inside components

I am currently in the process of upgrading an existing application from Ext 3.x to 4. I have successfully enabled Ext's scoped reset CSS option to prevent Ext from applying its CSS reset to my entire application. However, I am now facing a new issue. ...

Issue with Javascript form submission leading to incorrect outcomes

When setting the form action to a text retrieved from the database with an ID, I encountered a problem where it always displays the first ID even when clicking on text holding ID=2. Upon checking the page source, the correct IDs are shown for all texts. B ...

"Enhancing User Interaction with AngularJS: Leveraging ng-click and ng

Currently, I have a map with markers that trigger an overlay-div to open when clicked. <div class="map" ng-init="loadall()"> <a ng-click="details.show=!details.show" href="#/dealer/{{marker.id}}" class="marker" style="left:{{marker ...