Include a div element within the slider

In the process of developing a slider feature that includes both images and paragraphs on each slide, I have encountered a stumbling block while attempting to create a new div element. Despite trying various solutions, the methods that previously worked for an image-only slider seem ineffective now. The slider refuses to slide, and new divs fail to materialize. Can anyone shed light on what might be causing this issue? Below is the code snippet in question:

var slide = function () {

    if (number_of_image <= 1) number_of_image++;
    else number_of_image = 0;

    $('div.slider:first-of-type').after("<div class='slider'><img src='" + images[number_of_image] + "' alt='" + alts[number_of_image] + "' /></div>");

    var windowWidth = $(window).width();

    $('div.slider:last-of-type').css({
        'display': 'inline-block',
            'position': 'absolute',
            'top': $('div.slider:first-of-type').position().top + 'px',
            'left': windowWidth + 'px'
    });
    $('div.slider:first-of-type').animate({
        left: '-' + windowWidth + 'px'
    }, {
        duration: 2000,
        queue: false,
        complete: function () {
            $('div.slider:first-of-type').remove();
        }
    });
    $('div.slider:last-of-type').animate({
        left: 0
    }, {
        duration: 2000,
        queue: false
    });
}

var time = 10000;

var tick = function () {
    time -= 100;
    if (time <= 0) {
        slide();
        time = 10000;
    }
}

setInterval(tick, 100);

UPDATE: An error message "Uncaught TypeError: Cannot read property 'top' of undefined" is being triggered on this line of code:

'top': $('div.slider:first-of-type').position().top + 'px',

Answer №1

The issue is indicating that the value returned from the position on that specific line of code is undefined, leading to a lack of the top property.

This situation typically occurs when the position function is unable to determine the position of the elements. I tested your code and initially encountered the same error as you did. After adding

<div class="slider"></div>
elements to the page, the issue was resolved. You can see the updated code in action in this fiddle: http://jsfiddle.net/9rDAm/2/. Having elements that the position() function can calculate from should resolve the problem, ensuring that the elements are not hidden.

The excerpt below is extracted from the jQuery documentation for .position(): http://api.jquery.com/position/

Note: jQuery does not support obtaining position coordinates for hidden elements or considering borders, margins, or padding applied to the body element.

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

Automated file uploading with AJAX on Firefox

After inserting a row into the database, I want to automatically upload a PDF/XML file with no user involvement. The script should be able to identify the filename and location of the file. Is there a method to achieve this task? Share your ideas in the a ...

Metronome in TypeScript

I am currently working on developing a metronome using Typescript within the Angular 2 framework. Many thanks to @Nitzan-Tomer for assisting me with the foundational concepts, as discussed in this Stack Overflow post: Typescript Loop with Delay. My curren ...

What is the best way to calculate the number of squares required to completely fill a browser window in real-time?

I am creating a unique design with colorful squares to cover the entire browser window (for example, 20px by 20px repeated both horizontally and vertically). Each square corresponds to one of 100 different colors, which links to a relevant blog post about ...

Issue with integrating the jquery tokeniput plugin in asp.net mvc 3

Having trouble integrating the jQuery Tokeninput plugin into my MVC application. Something seems off with the setup... The Code I'm Using: <input type="text" id="MajorsIds" name="MajorsIds" /> <script type="text/jav ...

Using Jquery and css to toggle and display active menu when clicked

I am trying to create a jQuery dropdown menu similar to the Facebook notification menu. However, I am encountering an issue with the JavaScript code. Here is my JSFiddle example. The problem arises when I click on the menu; it opens with an icon, similar ...

Include the document when the query results in zero documents

Struggling to figure out how to add a document to a collection if a query returns no results. The current query lacks operators for checking the length or size of the result. How can this be achieved? The query in question: this.monthCollection = this.af ...

Shifting the Bootstrap sidebar

Here is a layout defined using Bootstrap: <div class="container-fluid"> <div onclick="smallSize()">Click</div> <div onclick="largeSize()">Click</div> <div class="row"> ...

Unveil the Expressjs middleware within the API Client

I am currently developing a Nodejs API Client with the following simple form: //client.js function Client (appId, token) { if (!(this instanceof Client)) { return new Client(appId, token); } this._appId = appId; this._token = tok ...

What is the best way to execute a Java script using AJAX from a different file?

I have included multiple ajax scripts in the main body of the Django template. However, when I try to run them from a separate JS file, they do not seem to work. This is an example of one of the working scripts within the body template: <!--Add product ...

Incorporating HTML content in email messages using a PHP mailer script

I have been exploring a way to incorporate HTML code into the email body using an AJAX PHP Form Mailer I discovered on this website: However, whenever I try to add my own HTML coding into the email body, it just displays the tags instead of rendering them ...

IE 11 does not support the use of absolute positioning with a height of 100%, however, this functionality works perfectly on Microsoft Edge

It appears that in IE 11, my absolutely positioned element is not displaying within another element with a height:100%. Strangely, it only works if I assign a fixed height to the element (even though its parent has a fixed height). Here is the HTML code: ...

Intel XDK problem with HTML5/CSS3 footers overlapping headers in my project

I am in the process of developing an application using drag and drop features from the Intel XDK/App Designer. The main concept behind this app is to provide users with basic tutorials and incorporate geolocation services. My approach involved following th ...

Activate the saturation toggle when a key is pressed in JavaScript

I am trying to modify a script that currently toggles the value of a variable when a key is pressed and then lifted. Instead of changing the variable value, I would like to adjust the saturation of the screen based on key presses and releases. How can I ac ...

What exactly is the significance of the </< in THREE.Camera.prototype.lookAt</<()?

After experimenting with THREE.js for a while, I came across something peculiar: When using Firefox and opening the developer console to type camera.lookAt (assuming your camera is named camera), it displays function THREE.Camera.prototype.lookAt</< ...

Conceal Element in React if it is the Final Item

Is there a way to hide the TimelineConnector if it is on the last item? I am looking for some guidance on how to achieve this. Please take a look at my codesandbox below: CLICK HERE {timelines.lastIndexOf(index) !== 1 ? <TimelineConnector /> : &quo ...

The "model" feature appears to be inactive

I discovered a fiddle with a simple radio button functionality that I forked and made some modifications to. The changes worked perfectly, you can check it out in this fiddle: Vue.component('radio-button', { props: ['id', 'v ...

Changing text and applying a different span class using a Jquery button toggle

My current issue involves a functional toggle button that smoothly slides a div up and down. However, I am facing problems when attempting to change the toggle button status: You can view a demonstration of my code here: http://jsfiddle.net/zwu0sn83/3/ B ...

Having trouble with Ajax and facebox integration issues?

My website utilizes ajax jquery and facebox for interactive features. You can check out a demo here. The div with the ID "#content" contains links to other pages that open successfully using facebox. However, when I reload the content of this div using aj ...

JavaScript Canvas - Preserve Image Transparency

I have been trying to download a snapshot of a canvas using the code below: var strMime = "image/png"; var canvas = document.getElementsByTagName('canvas')[0]; var link = document.createElement("a"); link.href = canvas.toDataURL( ...

How come the text is not centered when I use text-align:center; on my class "text5"?

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Homepage</title> ...