Using CSS3 to apply transformations to multiple divs based on their individual attributes

I am currently developing JavaScript code that will enable the use of HTML like the example below:

     <div class="box" data-vert-speed="7">ContentDiv1</div>
     <div class="box" data-hori-speed="10">ContentDiv2</div>
     <div class="box" data-rota-speed="5">ContentDiv3</div>
     <div class="box" data-vert-speed="2.4">ContentDiv4</div>
     <div class="box" data-hori-speed="1.3">ContentDiv5</div>
     <div class="box" data-rota-speed="2.3">ContentDiv6</div>

The aim is to have each div perform a CSS transform based on the scrolling of the page, with the rate of transformation determined by the attribute value.

The transforms are defined as "vert" for vertical, "hori" for horizontal, and "rota" for rotation.

Currently, the JavaScript code I have only works for one type of attribute and I am struggling to make it work for all three types of attributes.

     $.fn.moveItrota = function(){
      var $windowr = $(window);
      var instancesr = [];

      $(this).each(function(){
        instancesr.push(new moveItItemrota($(this)));
      });

      window.onscroll = function(){
        var scrollTopr = $windowr.scrollTop();
        instancesr.forEach(function(instr){
          instr.updater(scrollTopr);
        });
      }
    }

    $.fn.moveItvert = function(){
      var $windowv = $(window);
      var instancesv = [];

      $(this).each(function(){
        instancesv.push(new moveItItemvert($(this)));
      });

      window.onscroll = function(){
        var scrollTopv = $windowv.scrollTop();
        instancesv.forEach(function(instv){
          instv.updatev(scrollTopv);
        });
      }
    }

    $.fn.moveIthori = function(){
      var $windowh = $(window);
      var instancesh = [];

      $(this).each(function(){
        instancesh.push(new moveItItemhori($(this)));
      });

      window.onscroll = function(){
        var scrollToph = $windowh.scrollTop();
        instancesr.forEach(function(insth){
          insth.updateh(scrollToph);
        });
      }
    }



    //Rotation Scrolling ------------------------------------------------

    if ($('.box').attr('data-rota-speed')){
     console.log("found a rota");   
    var moveItItemrota = function(elr){
      this.elr = $(elr);
      this.speedr = parseInt(this.elr.attr('data-rota-speed'));
      console.log(this.speedr);
    };

    moveItItemrota.prototyper.updater = function(scrollTopr){
      var posr = scrollTopr / this.speedr;
      this.elr.css('transform', 'rotate(' + -posr + 'deg)');
    };

    $(function(){
      $('[data-rota-speed]').moveItrota();
    });

    };

    //Horizontal Scrolling ------------------------------------------------

    if ($('.box').attr('data-hori-speed')){
    console.log("found a hori");
    var moveItItemhori = function(elh){
      this.elh = $(elh);
      this.speedh = parseInt(this.elh.attr('data-hori-speed'));
      console.log(this.speedh);
    };

    moveItItemhori.prototypeh.updateh = function(scrollToph){
      var posh = scrollToph / this.speedh;
      this.elh.css('transform', 'translateX(' + -posh + 'px)'); 
    };

    $(function(){
      $('[data-hori-speed]').moveIthori();
    });

    };

    //Vertical Scrolling ------------------------------------------------
    if ($('.box').attr('data-vert-speed')){
    console.log("found a vert");

    var moveItItemvert = function(elv){
      this.elv = $(elv);
      this.speedv = parseInt(this.elv.attr('data-vert-speed'));
      console.log(this.speedv);
    };

    moveItItemvert.prototype.updatev = function(scrollTopv){
      var posv = scrollTopv / this.speedv;
      this.elv.css('transform', 'translateY(' + -posv + 'px)');
    };

    $(function(){
      $('[data-vert-speed]').moveItvert();
    });

    };

Answer №1

Upon reviewing your code, it appears that you have multiple data points linked to the same attribute. I would recommend separating them if possible. Based on the code provided, it seems that each element is associated with a specific movement type and speed. If my assumption is accurate, you could structure it as follows:

<div class="box" data-movement="vertical" data-speed="7">ContentDiv1</div>
<div class="box" data-movement="horizontal" data-speed="10">ContentDiv2</div>
<div class="box" data-movement="rotation" data-speed="5">ContentDiv3</div>
<div class="box" data-movement="vertical" data-speed="2.4">ContentDiv4</div>
<div class="box" data-movement="horizontal" data-speed="1.3">ContentDiv5</div>
<div class="box" data-movement="rotation" data-speed="2.3">ContentDiv6</div>

To implement this, you can retrieve the items in JavaScript and apply the respective CSS:

var boxItems = $(".box");
$.map(boxItems, function(item, i) {
   var movement = $(item).data("movement");
   var speed = $(item).data("speed");
   switch(movement) {
      case "horizontal": {
         // implement horizontal movement here
         break;
      }
      case "vertical": {
         // implement vertical movement here
         break;
      }
      case "rotation": {
         // implement rotation here
         break;
      }
   }
});

I have not included the actual movement code as I am uncertain if you are utilizing css transforms. However, here is a resource that explains how to apply them: http://www.w3schools.com/jsref/prop_style_transform.asp

I hope this information proves useful.

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

Create an asynchronous method within an object-oriented programming (OOP) class

Presenting my Activity class. export class Activity { _name: string _goIn: boolean constructor(name: string) { this._name = name; this._goIn = false; } isGoIn() { return this._goIn; } setGoIn() { // instructions to asyn ...

Tips for transmitting data from the server to the client side

From the code posted below, I am attempting to transfer the value access_token from the method fetchAuthenticationToken to the method fetch in Ws.js. In fetchAuthenticationToken, I receive the value for the access_token and then assign that value to both r ...

Retrieve the class name from a CSS stylesheet

How can I extract all the CSS class names from a CSS file? This is what my CSS file looks like: p.juicy{ margin-left:40px; } p.csBody{ text-align:justify; } p.csCode{ font-family:"Lucida Console", Monaco, monospace; background-color:sil ...

The Codepen demo for SemanticUI is not functioning properly

Click here to view the example on CodePen $('.ui.sidebar').sidebar({ context: $('.bottom.segment') }) .sidebar('attach events', '.menu .item'); I am currently trying to replicate this specific functiona ...

Ways to enlarge the parent container and reveal a concealed child element upon hovering without impacting neighboring containers

Currently, I am diligently working on the company service boxes and have a particular need... When hovering over: 1. The parent div should scale up and acquire box shadow without impacting the neighboring service boxes (it should appear to stand out above ...

How to automatically refresh a page in AngularJS after a POST request

After making a POST request, I attempted to use $state.reload in my controller to refresh the page. However, it is not updating the data on my page after registering the form. I have to manually refresh the page to see the correct data. .controller(' ...

What are the steps to setting up SystemJS with Auth0?

I am having trouble configuring SystemJS for Auth0 (angular2-jwt) and Angular 2.0.0-beta.6 as I keep encountering the following error message: GET http://localhost:3000/angular2/http 404 (Not Found)fetchTextFromURL @ system.src.js:1068(anonymous function) ...

Using JavaScript, the list of items (images) will be displayed and placed into HTML panels

Below is the layout structure on my website: <div class="panel-heading"><h3 class="panel-title">Suggestions</h3></div> <div class="panel-body"> <div class="col-md-7"> <h3><span class= ...

Combining React, Express, and Nodemailer poses challenges in rendering components and sending emails simultaneously

Looking to utilize client-side routing for my React app and also incorporate Nodemailer for sending emails. However, since Nodemailer cannot be used on the client-side, I need to implement it on the Express server. Here is how the server code looks like: ...

When clicking on links that are not within the ng-view element, you will be redirected to the

I'm having trouble coming up with a name for this question, but here's my current situation This is the structure of my template: ├── index.html ├── ... ├── account │ ├── index.html │ ├── authorizat ...

Personalize your message in a JavaScript alert using Bootstrap notifications

On numerous websites, a new visitor landing on the page is greeted with an alert notification that pops up in either the bottom right or left corner. The code below functions perfectly fine, except for my unsuccessful attempts to change the message text w ...

Having trouble with the unresponsive sticky top-bar feature in Zurb Foundation 5?

According to the information provided on this website, it is recommended to enclose the top-bar navigation within a div element that has both the class "contain-to-grid" and "sticky". However, I have noticed that while the "contain-to-grid" class exists in ...

Display the div only during the printing process

Imagine I have a situation where there is a block of content that I only want to show when printing. It looks something like this: <div id="printOnly"> <b>Title</b> <p> Printing content </p> </div&g ...

What is the reason for not encountering an error when reading an array beyond its index limit?

Recently, while working on a pre-existing website with JavaScript code, I made an interesting discovery. I noticed that the code was accessing array items in a unique way: var value = myArray[0, 1]; This seems to be retrieving the second item of the arr ...

javascript Arabic speech synthesis

Attempting to utilize SpeechSynthesisUtterance for Arabic language Successfully functioning with English content $(document).ready(function() { var u1 = new SpeechSynthesisUtterance('Hello world!'); u1.lang = 'en-US'; u1.pitch ...

I was caught off guard by the unusual way an event was used when I passed another parameter alongside it

One interesting thing I have is an event onClick that is defined in one place: <Button onClick={onClickAddTopics(e,dataid)} variant="fab" mini color="primary" aria-label="Add" className={classes.button}> <AddIcon /> & ...

Tips for transforming code with the use of the then block in javascript, react, and cypress

In my code snippet below, I have several nested 'then' clauses. This code is used to test my JavaScript and React code with Cypress. { export const waitForItems = (retries, nrItems) => { cy.apiGetItems().then(items => { if(items ...

Invoking a Vuex action inside another Vuex action

After transitioning to the Vuex store, I've been steadily moving forward. However, my current hurdle involves invoking an action from within another action in Vuex. My grasp on Vue.js is still a work in progress. Current versions Vue 3 Vuex 4 If nec ...

Running a Python Selenium script

I need some help executing this script using selenium. <div class="vbseo_liked"> <a href="http://www.jamiiforums.com/member.php?u=8355" rel="nofollow">Nyaralego</a> , <a href="http://www.jamiiforums.com/member.php?u=8870" rel="nofollo ...

Can I inspect the HTML source of GWT?

How can I access the HTML source code generated by GWT? Currently, I only see the DIV with a specific ID when viewing the source. Is there a way to view the entire HTML output? Is it possible to design my table in HTML using divs and lists, then wrap it i ...