Move the background image by scrolling it

Is there a way to scroll a background image until the end pixel and then go backwards to the beginning of the image, repeating this sequence continuously?

Currently, I have a code that scrolls the background image continuously in one direction. How can I modify it to achieve the desired effect?

CSS:

body{margin:0; border:0; background:url(ejemplo3.jpg) repeat-x;}

HTML:

<body></body>

JQuery:

var scrollSpeed = 50;

// set the default position
var current = 0;

// set the direction
var direction = 'h';

function bgscroll() {
    // scroll by 1 pixel at a time
    current -= 1;

    // move the background using background-position css properties
    $('body').css("backgroundPosition", (direction == 'h') ? current + "px 0" : "0 " + current + "px");
}

//Calls the scrolling function repeatedly
setInterval(bgscroll, scrollSpeed);

Answer №1

Having a background repeat-x will create a loop, causing the image to rotate in one direction only. If you set the image to no-repeat, you can modify your code like this:

/* Insert Background Image (add your own image) */

body{margin:0; border:0; background:url(dsc01549.jpg) no-repeat;}

/* Add Script */

// Global Variables

var scrollSpeed = 50;
// set the default position
var current = 0;
// image height & rotation complete
var _ht,_finishNRot=false;
// set the direction
var direction = 'h';
// create hidden image element to grab height of it for calculation purpose
var url = $('body').css('background-image').replace(/^url\(["']?/, '').replace(/["']?\)$/, '');
var bgImage = $('<img />');
bgImage.hide().bind('load', function(){ _ht = $(this).height(); });
$('body').append(bgImage);
bgImage.attr('src', url);

function bgscroll() {
// while rotation not completed 
if(_finishNRot==false){ current -= 1;} else {current+=1; } ;
// -ve Rotation completed
if(-(current)==_ht)_finishNRot = true;
// +ve Rotation completed
if((current)==0)_finishNRot = false;
// move the background with backgrond-position css properties
$('body').css("backgroundPosition", (direction == 'h') ? current + "px 0" : "0 " + current + "px");
}

//Calls the scrolling function repeatedly
setInterval(bgscroll, scrollSpeed);

I trust this information is beneficial to you.

Best regards, Ashok

Answer №2

If you're looking to adjust the height of your image and scroll through it, consider using 'background-repeat y' in your CSS without fixing the background image. This will enable you to smoothly scroll through the image while viewing it.

Answer №3

How about something as graceful as this example: http://jsfiddle.net/NicoO/fMHL4/ I would certainly enjoy seeing it displayed on a page like that ;)

@keyframes move-background
{
    0% { background-position:left top; }
    50% { background-position:left bottom; }
    100% { background-position:left top; }
}

html,body
{
    margin: 0;
    padding: 0;
    height: 100%;
    background-image: url(http://www.placehold.it/800x2000);
    transition-property: background-position;

    -webkit-animation: move-background 2s infinite; 
    -moz-animation:    move-background 2s infinite; 
    -o-animation:      move-background 2s infinite; 
    animation:         move-background 2s infinite; 
}

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

In mobile browsers, the text within the <pre> tags appears extremely small. How can I adjust the font

My issue is with preformatted text that displays correctly on desktop browsers but appears very small on mobile devices in comparison to regular text. Adjusting the size using ems or percent causes it to be too large on desktop screens. Despite searching e ...

JQuery is used to create a pop-up box

As a newcomer to JQuery, I am working on implementing a pop-up box on my webpage. Utilizing a jQuery plugin derived from Ray Stone's leanModal: (function($) { $.fn.extend({ leanModal: function(options) { var defaults = { top: 10 ...

Reposition the navbar nav to the top right corner of my website using Boostrap

I'm completely new to this subject. Currently, I've been following an online tutorial on HTML/CSS/Bootstrap. One thing I want to do is move the navbar to the top right of the page, like what you see in the image below. I manually added a mockup ...

Retrieve the Excel document on the client's end using a Webservice in conjunction with jQuery Ajax

I am looking to export data into an Excel file on the server-side and then download it to the client-side upon clicking a button. I have created a web service method and made an AJAX call from jQuery. While I was able to successfully create the Excel file ...

Reorder the nested list structure

Hello there and thank you for stopping by! I am facing a challenge with a list containing multiple nestings. I am interested in changing the order of these two lists, and I am curious if this is achievable using only CSS. List item 1 List item 2 List ...

Building CSS columns

Similar Inquiry: Creating dual columns in HTML/CSS layout I'm exploring ways to achieve a two-column layout within a wrapping div element. Currently, I have the following CSS code snippet which centers a div inside the browser: .wrapper {width: ...

Enhance your webpage with custom styling using the html() method in jQuery

Adding style to my website using the .html() method is something I'm looking to do. I've attempted this: Using jQuery: if ($('#checkbox:checked') > 0) { $("body").html(" <style> .selected{ ...

Developing two HTML tables utilizing JavaScript

I've encountered an issue while trying to generate 2 dynamic html tables using JavaScript with data from HTML inputs. Successfully creating the first table, I faced difficulties in creating another table utilizing different input fields on the same pa ...

Modify the background color of one div based on the visibility of another div

My carousel consists of three divs representing a Twitter post, a Facebook post, and a LinkedIn post. These are contained within another div called #social-media-feeds. I am curious if it is feasible to adjust the background color of #social-media-feeds d ...

Initiating a dual XMLHttpRequest operation

Embarking on my initial AJAX project, I am delving into the realm of crafting a dual AJAX function. The primary goal is to utilize the output string ("venue_ID") of the first function as an input for the second AJAX function in order to generate a string ( ...

Using jQuery to toggle the selection of multiple checkboxes

Let's start fresh, no need to worry! This is simply a jQuery question ;) I am currently working on a PHP code where the user sends a query to our database. The form then displays sets of results grouped in tables, each with checkboxes to select the d ...

Is there a way to upload files in AngularJS without using AJAX or jQuery?

Currently, I am looking to create a gallery that allows for the uploading of multiple images. While I have come across some options that utilize ajax to immediately send the files, I prefer a solution that involves form submission. In addition, I would li ...

What is causing this div, which has a selector with a fixed position, to be unable to modify its left property?

I'm having trouble understanding why the css selector holder2 in my html file, with a fixed position, won't allow me to change its left property. It seems like I can only adjust the top property. If I attempt to modify the value of the left prope ...

What is the best way to use canvas to precisely draw a line on the display at specific absolute coordinates?

As a newcomer to working with canvas and SVG, I am trying to create a line between two specific coordinates. For example, if I have two rectangles, I need to draw a line connecting their centers: https://i.sstatic.net/Rc6qA.png Here is what I have tried ...

Constructing a dynamic invocation to a jQuery extension

Looking for the most effective way to construct a call to a jQuery plugin, I have a specific setup in mind: jQuery("#wrapper").myPLugin({ direction: direction, switch myOption { case "small": items:10, case "big": ...

Fixing My Code with JQuery Tabs and Hyperlinking

I have come across a problem while using multiple pages with jQuery tabs. Let's consider Page1.html with #tab1 and #tab2, and Page2.html with #tab3 and #tab4. Here are the issues I am facing: 1) Within the tab content of Page1.html#tab2, there is a h ...

Click on the hyperlink to adjust the background size of an inline list item

I created a navigation bar using inline display for the li elements. I want my last column to have a defined height background. However, it is only displaying a background behind the name of the column. Here is the relevant section from style.css: #navi ...

Is it recommended to apply the ARIA directory role to a breadcrumb navigation list?

Currently, I am working on enhancing the accessibility of a breadcrumbs component that is structured around a <ul> element. In my quest for solutions, I came across the concept of ARIA roles and specifically the directory role. While it seems like a ...

The column is not properly aligned

I am facing a challenge in aligning 3 elements using bootstrap while working with Angular 8. To include only the necessary CSS from Bootstrap (such as col-md and col classes), I have added the following to my styles array: "styles": [ "src/ ...

The formatting for a class that was added using ClassList isn't functioning as expected

Despite my code appearing correct, the styles are not being applied even though the class is added. It was functioning perfectly before, so I'm not sure what caused this issue now. Any assistance would be greatly appreciated! JavaScript code: let max ...