Step-by-step guide on crafting a scrolling marquee with CSS or Javascript

I am in need of creating two marquees for a website project. The first marquee should showcase a repeating image while the second one should display links, both spanning the browser window at any size. It is crucial that the marquee items are displayed from the start and do not take time to appear on screen. Additionally, I require each item to be spaced about 20px/30px apart. An important feature is that when a user hovers over the marquee, it should pause moving across the page.

For this project, I have decided to incorporate a marquee displaying the client's logo on one page and on another page, a marquee showcasing links to their social media profiles. However, calculating the necessary animation duration based on the text or image size to achieve an infinite appearance has proven challenging for me. After exploring CSS options and seeking advice without much success, it seems Javascript is the recommended approach. While I am new to Javascript and feeling quite lost, I found a similar solution here: . To visualize my goal, you can refer to this example: (specifically the bottom marquee moving left to right without overlapping). Attempting to implement the desired effect, I used this code snippet as a reference: https://codepen.io/jamesbarnett/pen/kfmKa.

body { 
  margin: 0;
  font-family: "UniversLTPro-Ex";
  font-size: 30px;
}

a {
    text-decoration: none;
    color: #000;
}

.marquee {
  height: 35px;
  width: 100%;

  overflow: hidden;
  position: relative;
  background-color: #e9e5fb;  
  border-top: 1px solid black;
  border-bottom: 1px solid black;
  padding: 8px 0 4px 0;
}

.marquee div {
  display: inline-block;
  width: 300%;
  height: 40px;

  position: absolute;
  overflow: hidden;

  animation: marquee 12s linear infinite;
}

.marquee span {
  float: left;
  width: 25%;
}

@keyframes marquee {
  0% { left: 0; }
  100% { left: -150%; }
}
        <div class="marquee">
            <div>
                <span><a href="#">twitter</a></span>
                <span><a href="#">instagram</a></span> 
                <span><a href="#">pinterest</a></span>
                <span><a href="#">spotify</a></span> 
                <span><a href="#">magazine</a></span>
            </div>
        </div>

My attempts so far have faced various problems. The marquee does not loop infinitely, the hover pause functionality remains unresolved, and the spacing between items is too wide. Any assistance on addressing these issues would be highly appreciated. Thank you!

Answer №1

There are several methods to achieve the desired outcome, and you have the freedom to select the one that suits you best.

  • Utilizing the HTML marquee tag
  • Employing CSS animation along with text-indent property
  • Implementing CSS animation in conjunction with position relative
  • Using pure JavaScript without any libraries
  • Utilizing JQuery for animation effects

/* Vanilla JS */

var rightJS = {
  init: function(){
    rightJS.Tags = document.querySelectorAll('.rightJS');
    for(var i = 0; i < rightJS.Tags.length; i++){
      rightJS.Tags[i].style.overflow = 'hidden';
    }
    rightJS.Tags = document.querySelectorAll('.rightJS div');
    for(var i = 0; i < rightJS.Tags.length; i++){
      rightJS.Tags[i].style.position = 'relative';
      rightJS.Tags[i].style.right = '-'+rightJS.Tags[i].parentElement.offsetWidth+'px';
    }
    rightJS.loop();
  },
  loop: function(){
    for(var i = 0; i < rightJS.Tags.length; i++){
      var x = parseFloat(rightJS.Tags[i].style.right);
      x ++;
      var W = rightJS.Tags[i].parentElement.offsetWidth;
      var w = rightJS.Tags[i].offsetWidth;
      if((x/100) * W  > w) x = -W;
      if (rightJS.Tags[i].parentElement.parentElement.querySelector(':hover') !== rightJS.Tags[i].parentElement) rightJS.Tags[i].style.right = x + 'px';
    } 
    requestAnimationFrame(this.loop.bind(this));
  }
};
window.addEventListener('load',rightJS.init);

/* JQUERY */

$(function(){
  var rightJQ = {
    init: function(){
      $('.rightJQ').css({
        overflow: 'hidden'
      });
      $('.rightJQ').on('mouseover',function(){
        $('div', this).stop();
      });
      $('.rightJQ').on('mouseout',function(){
        $('div', this).animate({
          right: '100%'
        }, 14000, 'linear' );
      });
      rightJQ.loop();
    },
    loop: function(){
      $('.rightJQ div').css({
        position: 'relative',
        right: '-100%'
      }).animate({
        right: '100%'
      }, 14000, 'linear', rightJQ.loop);
    }
  };
  rightJQ.init();
});
marquee { background: #0089fa; }

.rightTI { background: #ff002b;
  white-space: nowrap; 
  overflow: hidden;
  animation: marquee 18s linear infinite;
}
.rightTI:hover {
  animation-play-state: paused;
}
@-webkit-keyframes marquee {
  0% {text-indent: 100%;}
  100% {text-indent: -100%;}
}

.rightCSS { 
  background: #a35dc1;
  overflow: hidden;
} 
.rightCSS div {
  position: relative;
  animation: CSSright linear 18s infinite;
} 
@keyframes CSSright {
  0% { right: -100% }
  100% { right: 100% }
}
.rightCSS:hover div {
  animation-play-state: paused;
}

.rightJS { background: #ffa900; }

.rightJQ { background: #00a753; }

.li {
  float: left;
  width: 80%;
  padding: 1%;
  margin: 1% 10%;
  height: 20px;
  border-radius: 0.5em;
  box-shadow: 0 0.1em 0.5em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<marquee class="li" direction=”right” onmouseover="stop()" onmouseout="start()">★ HTML tag &lt;marquee&gt; ★</marquee>
<div class="rightTI li">★ CSS animation and text-indent ★</div>
<div class="rightCSS li"><div>★ CSS animation and position relative ★</div></div>
<div class="rightJS li"><div>★ pure javascript ★</div></div>
<div class="rightJQ li"><div>★ Jquery animate ★</div></div>

Answer №2

While CSS is usually the go-to for styling, in this particular case, the requirement calls for a hover pause and resume feature that cannot be achieved with CSS alone. To accomplish this, JavaScript comes into play. By setting up a time interval that adjusts the left property of an element in increments, we can move the element to the left at regular intervals. When hovered over, the time interval is cleared, halting the animation at its current position. Once the mouse moves away, the interval resumes, seamlessly continuing the animation.

Answer №3

Your issue has been resolved, lucygoosey. If you desire further assistance, exert more effort in that direction.

body { 
  margin: 0;
  font-family: "UniversLTPro-Ex";
  font-size: 30px;
}

a {
    text-decoration: none;
    color: #000;
}

.marquee {
  height: 35px;
  width: 300%;
  position: relative;
  padding: 8px 0 4px 0;
  border: none;
}

.marq{
  background-color: #e9e5fb;
  border-top: 1px solid black;
  border-bottom: 1px solid black;
  
}


.marquee span {
  float: left;
  width: 300px;
}

@keyframes marquee {
  0% { left: 0; }
  100% { left: -150%; }
}
<div class="marq">  
<marquee onmouseover="this.stop();" onmouseout="this.start();">
           <div class="marquee">
                <span><a href="#">twitter</a></span>
                <span><a href="#">instagram</a></span> 
                <span><a href="#">pinterest</a></span>
                <span><a href="#">spotify</a></span> 
                <span><a href="#">magazine</a></span>
          </div>
 </marquee>     
</div>

To learn more about the marquee tag, click here

Marquee tag documentation

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

Issue with Bootstrap Table Style When Using window.print();

The color of my Bootstrap table style is not displaying correctly in the print preview using window.print(). Here is a screenshot showing that the table style is not working properly: https://i.stack.imgur.com/eyxjl.jpg Below is the code I am using: < ...

Plugin refresh after callback

I have a webpage that features a row of buttons at the top, followed by some content below. Whenever one of the buttons is clicked, the content is updated using UpdatePanels. Within this content, I am attempting to incorporate the royal slider plugin, wh ...

Encountering this issue despite confirming the presence of data on the line before! What could be the missing piece here? Error: Unable to access property 'includes' of undefined

Here is the situation.. I'm retrieving data from a database and storing it in an array of objects. These objects represent articles. I am working on implementing a filter system based on categories. The objective is to apply a filter that checks for a ...

What are the top methods for interacting between Server APIs and Client-Side JavaScript?

Presently, I am utilizing setTimeout() to pause a for loop on a vast list in order to apply some styling to the page. For example, For example: How I utilize setTimeOut: I use setTimeout() to add images, text and css progress bars (Why doesn't Prog ...

Presenting JSON information in a concise and visually appealing manner

How can I extract a value from JSON data and display it in an HTML text field? The JSON data looks like this: {"name":"paul"}, but I only want to display "paul" in my text field. Here is my code in CodeIgniter PHP: $data['name'] = $this->name ...

Arranging items by their total sum of arrays in React.js

I'm working with data.js where I have stored my JSON information. Here's a snippet: [ { name: 'Adam Doe', city: 'New York', mark: [8,10,10,10] }, { name: 'Catlyn Stronk', ...

Firefox encounters a border-radius glitch

Having an issue with the border-radius function in Firefox. After applying it, I notice a strange space or border around the item. Does anyone know if this is a bug specific to Firefox or if there is a solution for it? Here is an example of the problem: J ...

I am experiencing an issue where Discord.js is unable to assign a role to a new member upon joining my server

I'm trying to set up my bot to automatically assign a specific role to new members when they join the server. However, I keep encountering a strange error that I can't seem to figure out. Here is the code snippet in question: const { GuildMember ...

Guide to extracting a key from the route module with the help of vuex-router-sync

I have a Vuex store setup as shown below, and I am using vuex-router-sync to keep it in sync. This plugin adds a router module to my store. However, I am unsure of how to retrieve this object from the store since there are no associated getters with this m ...

What are some techniques for animating SVG images?

Looking to bring some life to an SVG using the jQuery "animate" function. The plan is to incorporate rotation or scaling effects. My initial attempt with this simple code hasn't yielded the desired results: $("#svg").animate({ transform: "sc ...

Display data fetched from concurrent Ajax calls in a React Component

I am currently in the process of converting my original project to Reactjs. Since I am new to this and it's my first application, I could use some guidance on how to effectively implement this in a React-friendly way and enhance both my skills and the ...

@HostBinding in Angular 2 does not trigger change detection

When using @HostBinding in conjunction with Chrome's Drag and Drop API, the code looks like this: @Directive({ selector: '[sortable-article]' }) export class SortableArticleComponent { @HostBinding('class.dragged-element') ...

Processing JSON data from an array in PHP

Currently, my code involves utilizing an AJAX request to retrieve data from a database dynamically. The data received is processed by the PHP function json_encode() before being sent back to AJAX. Upon receiving the data through the AJAX request, it is for ...

A step-by-step guide on making an animation series with html and css keyframes

I've been working on creating a captivating animation using HTML and CSS keyframes, but I seem to have hit a roadblock. Despite trying different rotations and transforms, I can't seem to achieve the desired effect depicted in the image below. The ...

Sending a string data from client to a MongoDB database using Express.js and Node.js with the help of Sails framework

Need help with sending a string from client to mongoDB using Sails The "val" variable represents a string sent in real time from the client to the server database POST Form( is using HTML the best approach here? ) <!DOCTYPE html> <html> < ...

The functionality to apply a color class to a navbar item when clicked is malfunctioning

I'm attempting to create a navigation bar using text that toggles the visibility of different divs. I want the selected option to appear in red, indicating it has been chosen, while deselecting any other options. I am new to JavaScript and thought add ...

Encountering difficulties in storing array data into MongoDB collection

I am facing an issue with connecting to two different MongoDB instances using different URLs. One URL points to a remote connection string while the other one is for a local MongoDB instance. Initially, I establish a connection to MongoDB using MongoClient ...

Creating an interactive dropdown feature using AngularJS or Ionic framework

$scope.AllCities = window.localStorage.getItem['all_cities']; <div class="row"> <div class="col"> <div class="select-child" ng-options="citie.name for citie in AllCities" ng-model="data.city"> <label&g ...

VeeValidate fails to validate input fields in a form that is constantly changing

My goal is to create dynamic forms with validations using veeValidate in Vue.js. I am attempting to achieve this by storing an array of objects within the component's data. For instance: data(){ return{ inputs: [ { id: 1, lab ...

After combining two files in browserify, the error message "XXX.foo is not a function" appeared

When using browserify to bundle two JavaScipt files into one with the command: browserify X1.js X2.js --standalone XXX > bundle.js The file X1.js contains a function like this: function foo() { console.log("something") } And it is being exported i ...