Incorporating HTML5 transitions into your website

After researching HTML5 transitions and adapting some examples, I finally achieved the desired effect.

<!DOCTYPE html>
<html>
<head>
    <style>
        div {
          width: 50px;
          height: 50px;
        }

        div.myDiv {
          position: absolute;
          -webkit-transition-property: top, opacity;
          -webkit-transition-duration: 1s, 1s;
          -webkit-transition-timing-function:ease-in-out, ease-in-out;

          -moz-transition-property: top, opacity;
          -moz-transition-duration: 1s, 1s;
          -moz-transition-timing-function:ease-in-out, ease-in-out;

          -o-transition-property: top, opacity;
          -o-transition-duration: 1s, 1s;
          -o-transition-timing-function:ease-in-out, ease-in-out;

          transition-property: top, opacity;
          transition-duration: 1s, 1s;
          transition-timing-function:ease-in-out, ease-in-out;
        }
        #one {
          top: 0px;
          background-color: blue;
          opacity: 1;
        }

        #two {
          top: 50px;
          background-color: green;
          opacity: 0;
        }

        #three {
          top: 100px;
          background-color: red;
          opacity: 0;
        }

        #container {
          width: 50px;
          height: 150px;
          position: relative;
          overflow:hidden;
        }
    </style>
    <script>

    function one() {
      document.getElementById('one').style.top = "0px";
      document.getElementById('two').style.top = "50px";
      document.getElementById('three').style.top = "100px";

      document.getElementById('one').style.opacity = "1";
      document.getElementById('two').style.opacity = "0";
      document.getElementById('three').style.opacity = "0";
    }
    function two() {
      document.getElementById('one').style.top = "-50px";
      document.getElementById('two').style.top = "0px";
      document.getElementById('three').style.top = "50px";

      document.getElementById('one').style.opacity = "0";
      document.getElementById('two').style.opacity = "1";
      document.getElementById('three').style.opacity = "0";
    }

    function three() {
      document.getElementById('one').style.top = "-100px";
      document.getElementById('two').style.top = "-50px";
      document.getElementById('three').style.top = "0px";

      document.getElementById('one').style.opacity = "0";
      document.getElementById('two').style.opacity = "0";
      document.getElementById('three').style.opacity = "1";
    }
    </script>
</head>
<body>
<div id='container'>
    <div class="myDiv" id='one'>
    </div>
    <div class="myDiv" id='two'>
    </div>
    <div class="myDiv" id='three'>
    </div>
</div>
<input type='button' onclick='one();' value='one!'></input>
<input type='button' onclick='two();' value='two!'></input>
<input type='button' onclick='three();' value='three!'></input>
</body>
</html>

I came across advice that it's not recommended to change CSS properties with JavaScript. It's considered a bad practice. Is there a more elegant and effective way to achieve this?

Any idea? (fiddle here)

Answer №1

I don't think it's necessarily a bad practice to modify CSS properties using JavaScript. However, if there is a chance that some users might have JavaScript disabled, it may be wise to avoid changing fundamental site properties in this way.

You can refactor your JavaScript code as shown below, providing the added benefit of easily adding or removing boxes (view example fiddle here):

// Define different colored boxes
var boxes = ['blue', 'green', 'red'];
var height = 50;

// All boxes will be placed within a single moving div for easier management
var slider = document.getElementById('slider');
var div;

for (var i = 0; i < boxes.length; i ++) {

  // Create a box element for each color
  div = document.createElement('div');

  div.setAttribute('id', 'box_' + i);
  div.setAttribute('class', 'myDiv');

  div.style.background = boxes[i];
  div.style.top = (i * height) + "px";
  div.style.opacity = (i == 0) ? 1 : 0;

  // Add the box to the slider div
  slider.appendChild(div);
}

function slide(index) {

  // Move the slider to display the selected box
  var top = (index * height) * -1;

  document.getElementById('slider').style.top = top + 'px';
  toggleVisible(document.getElementById('box_' + index));
}

// Hide non-selected boxes and show the selected one
function toggleVisible(show) { 

  var div;

  for (var i = 0; i < boxes.length; i ++) {
    div = document.getElementById('box_' + i);
    div.style.opacity = (div === show) ? 1 : 0;
  }
}

HTML:

<div id='container'>
  <div id='slider'></div>
</div>

<input type='button' onclick='slide(0);' value='one!'></input>
<input type='button' onclick='slide(1);' value='two!'></input>
<input type='button' onclick='slide(2);' value='three!'></input>

CSS:

div {
  width: 50px;
  height: 50px;
}

div.myDiv {
  position: absolute;
  -webkit-transition-property: opacity;
  -webkit-transition-duration: 1s, 1s;
  -webkit-transition-timing-function:ease-in-out, ease-in-out;

  -moz-transition-property: opacity;
  -moz-transition-duration: 1s, 1s;
  -moz-transition-timing-function:ease-in-out, ease-in-out;

  -o-transition-property: opacity;
  -o-transition-duration: 1s, 1s;
  -o-transition-timing-function:ease-in-out, ease-in-out;

  transition-property: opacity;
  transition-duration: 1s, 1s;
  transition-timing-function:ease-in-out, ease-in-out;
}

#container {
  width: 50px;
  height: 150px;
  position: relative;
  overflow:hidden;
}

#slider { 
  position: absolute;
  -webkit-transition-property: top;
  -webkit-transition-duration: 1s, 1s;
  -webkit-transition-timing-function:ease-in-out, ease-in-out;

  -moz-transition-property: top;
  -moz-transition-duration: 1s, 1s;
  -moz-transition-timing-function:ease-in-out, ease-in-out;

  -o-transition-property: top;
  -o-transition-duration: 1s, 1s;
  -o-transition-timing-function:ease-in-out, ease-in-out;

  transition-property: top;
  transition-duration: 1s, 1s;
  transition-timing-function:ease-in-out, ease-in-out;
}

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

Position the input alongside the icon

I am looking to enhance my bootstrap input field by adding an eye icon: https://i.sstatic.net/Lin1W.png <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" /> <link href="https://cdn ...

What does "cascading" refer to in the context of Cascading Style Sheets?

Similar Query: Explaining the concept of "cascading" in CSS Can you clarify the term "cascading" within Cascading Style Sheets? ...

When the resolution changes, the text shifts away from the bar in CSS

When I adjust the resolution of my display, the text on my top bar also changes. Can anyone help me fix this issue? In normal view: With changed resolution or smaller browser window: This is my HTML code: <body> <div class="top-panel"> ...

.parseXML yields no results

I am struggling to interpret a response from a server that should be in XML format. While I am new to web development, I am trying to quickly grasp JavaScript for an assignment. Unfortunately, I cannot control the server. My code snippet is as follows: . ...

Using multiple MaterialUI components in a JavaScript page with React can pose challenges

Incorporating multiple MaterialUI Cards in my project, I encountered an issue where all the cards would expand or the select values would change simultaneously. Despite using unique key values and mapped components with distinct keys, the problem persisted ...

"Exploring the challenges of implementing a jquerytools tooltip with AJAX

Currently, I have set up an ajax call to run every 15 seconds. The issue arises when the ajax call disables the tooltip if it's open at that moment for a particular item. This results in the destruction of only the tooltip being displayed, leaving oth ...

Enforcing character limits in summernote

Is there a way to set a character limit on Summernote? I've tried setting maxlength on the textarea without success. Check out the Summernote GitHub page $("#textareaid").summernote({ toolbar:[ ['style', ['style']], ...

Contrasting behavior in JavaScript experienced in development versus production environments

I've been working on an application that, when given certain data, generates a diagram using JavaScript in conjunction with the kineticJS framework. During development, everything is smooth sailing, but once deployed to production (Heroku), things st ...

Having trouble getting a Bootstrap 4 modal to load properly when triggered by a hyperlink

My modal contact form is giving me trouble. It's not loading despite my best efforts to fix it. Below is the code snippet: <div class="row py-2"> <div class="col-sm-3 hidden-md-down"> <a class="bg-circle ...

What is the method for dynamically updating and showcasing a JSON file upon the click of a button?

I'm currently developing an add-on that will display a panel with checkboxes and a save button when a toolbar button is clicked. The goal is to allow users to select checkboxes, then save the selected data in a JSON file that can be accessed and updat ...

Stopping Form Submission with MUI TextField

I am currently creating a form using React along with MUI. I'm trying to figure out how to prevent the form from being submitted when the user hits the enter key. Usually, I would use e.preventDefault(), but for some reason it's not working in th ...

Securing your Node.js connect-rest REST API with OAuth: A comprehensive guide

After conducting an extensive search on Google for examples related to my query, I was left empty-handed due to the generic name of the "connect-rest" package. My objective is to secure a server side API that I have built using the Node module "connect-re ...

html - generating a block of code

Does anyone have any tips on creating a block like this one using CSS and HTML: Check out this image for reference I want to streamline the process and make it faster, any suggestions? ...

Tips for transferring data from Express to .ejs file during redirection in Node.js

When I submit the login form in my login.ejs file, the page redirects if the details are correct. If the password is wrong, however, I want to display a message in the .ejs file indicating this. Below are the details: Here is the code in my app.js file - ...

Modifying the CSS class depending on the percentage value

Check out the most recent JSFiddle here. Markup: <table id="math-table"> <tr> <td><input type="text" id="A1" name="A" value=""></td> <td><input type="text" id="B1" name="B" value="">< ...

Utilizing arrays in JavaScript alongside jQuery's methods such as $.inArray() and .splice()

I am currently dealing with an array that is limited to containing 12 values, ranging from 1 to 12. These values can be in any order within the array. My task is to iterate through the array and identify the first unused value, assigning it to a variable. ...

Leveraging jQuery to dynamically load an icon based on the content within a <label> tag

I manage a website that dynamically fetches content from a database, with varying contents for each label. For example, one label may be generated as General:, while another may be generated as TV:. My question is, can jQuery be used to replace the text NA ...

(Monetate) Resolving the issue of delayed transition between the <a> element and CSS arrow in the breadcrumb menu utilizing HTML/CSS/jQuery

Recently, I've been working on implementing a breadcrumb-style checkout progress indicator on my website using a code generator created by an incredible developer named Jonas Ohlsson. This feature utilizes HTML, CSS, and jQuery and is integrated into ...

Cease the execution of processes once a Promise has been rejected

My current code is functioning correctly, but I am facing an issue where if an error occurs, I want it to halt all other promises in the chain. Specifically, when chi.getCommand(val1, val2) returns a reject and triggers the exception catch block, I need to ...

Encountering error ORA-12514 when utilizing the node oracle-db npm package

At the moment, I am immersed in a project that relies on utilizing oracle for its backend. Following the instructions provided in this link, I successfully installed node-oracledb on my Mac using npm. The contents of my file are as follows: var oracledb = ...