Arrange sibling div elements horizontally using jQuery

I am facing an issue with aligning the thumbs horizontally as they are currently being displayed one on top of the other. My requirement is to have them spaced 5px apart.

To achieve this, I need to use absolute positioning. This will allow me to control the layout so that when a thumb is clicked, it enlarges and the ones to its left disappear to the left while those to its right move to the right.

Here is the HTML code:

<div class="portItem">
    <div class="itemContent-wrap">
        <div class="itemContent">
            <div class="container">
                <div class="thumbWrap">
                    <div class="thumb"></div>
                    <div class="thumb"></div>
                    <div class="thumb"></div>
                    <div class="thumb"></div>
                </div>
            </div>
        </div>
    </div>
</div>

And here is the CSS code:

.thumb {
  height: 200px;
  width: 450px;
  position: absolute;
  display: inline-block;
  background: #D0E182;
  margin-top: 25px;
  margin-right: 5px;
  transition: all 1s ease-in-out;
  top: 0;
  left: 0;
}

For JavaScript functionality, I have the following code:

$(document).ready(function(){ 
    $('.portItem').each(function() {
        $('.thumb', this).each(function(i) {
              $('.thumb').css('left',40*i);
         }).appendTo('.body');
     });
});

You can view the working example in this Fiddle: http://jsfiddle.net/nTHDk/14/

Thank you for your assistance!

Answer №1

There are several errors in your code that need to be addressed:

Check out the revised Fiddle

  1. Jquery wasn't added to your fiddle.
  2. You don't need to include the document.ready function in the fiddle.
  3. Use $(this).css('left',40*i +"px"); for each selection, paying attention to this and px.
  4. The size of your boxes was too large to see the movement clearly, so I decreased their sizes.
  5. I eliminated the appendTo function since the elements are already present in your DOM (were you trying to move them somewhere else?).
  6. If you intend to use the appendTo function, correct the selector to $('body').

Answer №2

$('.thumb').css('left',40*i); should actually be $(this).css('left',40*i);. You already have the correct element selected at that point, so there's no need to select all elements with the class .thumb.

Link to example

Answer №3

Update the CSS from using position:absolute to position:relative and change $('thumb').css('left', 40*i) to $(this).css('left',40*i);

The adjustment in JavaScript may not be essential, but your current approach is repetitive. Switching to relative positioning in CSS will ensure proper spacing. With position:absolute, all elements stack on top of one another.

Answer №4

To start, make sure to include jQuery in your code snippet. Additionally, it seems like you are incorrectly manipulating the .thumb elements within the inner each loop. To properly target these elements, you should use $(this) as shown below:

$(document).ready(function(){ 
    $('.portItem').each(function() {
        $(this).find('.thumb').each(function(i) {
              $(this).css('left',50*i);
         }).appendTo('.body');
     });
});

You can view the updated version on this Fiddle

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

Error in Node.js (NPM Error)

Recently, I purchased a VPS running Ubuntu 14.4 and successfully installed Node.js 1.4. However, when attempting to run my script (node tradebot.js), I encountered the following error message! :-/ module.js:327 throw err; ^ Error: Cannot find ...

Secured interactions following authentication using React Query and NextAuth

After successfully signing in to my Nextjs app using NextAuth, I encountered an issue with sending authenticated requests to my API. The data returned after signing in appears to be for an unauthenticated user. I suspect that the problem lies in React Que ...

What is the method for adding a prefix to every line in JavaScript?

I'm currently working on a React project and dealing with a string that may contain newlines. I'm looking for the most efficient way to inject a symbol at the start of each line. I've considered exploding the string into an array and adding ...

Arranging an array containing three elements

As I work on my angular app, I have come across the following array: [ { "Name": "Jack", "IncomingTime": "2020-06-19T11:02+00:00", "Outgoingtime": "2020-06-19T11:07+00:00" ...

Think about using floated elements to determine the width of blocks

Consider this example HTML markup (link to jsFiddle): <div style="float: right; width: 200px; height: 200px; background-color: red; margin: 0 20px 0 30px;"> Block 1 </div> <div style="height: 100px; background-color: green;">Block ...

Body Zoom Browser

My website features buttons for zooming in and out, labeled as A + and A-. I wanted to make sure that the entire body of the website could be magnified easily. That's why I came up with this code: <html> <body> <style> .cont ...

Connecting an Angular application to a URL hosted on localhost

I am currently working on an Angular project where one of the links needs to redirect to a different website. During development, this link points to a localhost URL like localhost:4210. However, due to security reasons in Angular, using such URLs is cons ...

Execute consecutive Angular2 functions in a sequential manner, one following the next

In my Angular2 project, I have a service that fetches data for dropdown menus on a form. However, when I call this service multiple times with different parameters in the form component initialization, only the last call seems to work, overriding the previ ...

What is causing the issue of the div not being removed from the label renderer in three.js

Hello, I've been trying to solve this issue for the third time now without much success. The problem I'm facing is related to creating a div at runtime and then attempting to remove it after clicking on it. Although I've tried removing the d ...

Issue with Sass @use failing to load partial

I'm currently facing an issue while trying to import a sass partial called _variables.scss into my main stylesheet named global.scss. Every time I compile the sass code, I encounter the following error message: Error: Undefined variable. Here is the ...

Mozilla Firefox is having trouble rendering HTML elements

While a webpage loads perfectly in Chrome, it seems to be causing some issues in Firefox. Can someone please shed some light on what the problem might be and suggest a solution? Please visit this Link in both Chrome and Firefox to see the difference. Chr ...

Inquiring Mind: jQuery Box

I am using a jQuery boxy plugin to display my captcha overlay: <script> $(document).ready(function() { var zahl1 = Math.floor(Math.random()*11); var zahl2 = Math.floor(Math.random()*31); //$("#cap").html("Wie viel ist "+zahl1+" + "+z ...

Debugging the Force-Directed D3 Graph

I stumbled upon a fantastic article that provided a detailed guide on creating a beautiful D3 force layout graph. However, I'm facing some difficulties with the JSON source: The "links" attribute in the author's JSON doesn't seem clear to m ...

Tips for removing empty space caused by the iPhone notch on your webpage

Hey there, I'm struggling to remove the blank space on my iPhone with a notch at the top of the screen. Do you have any advice on how to change the background color from the default white? My website is live and you can check it out at . I've att ...

Link a YAML file with interfaces in JavaScript

I'm currently learning JavaScript and need to convert a YAML file to an Interface in JavaScript. Here is an example of the YAML file: - provider_name: SEA-AD consortiumn_name: SEA-AD defaults: thumbnail Donors: - id: "https://portal.brain ...

Contrasting float-start and start-0 characteristics

I'm attempting to recreate the layout shown in this image using HTML and Bootstrap 5: https://i.sstatic.net/R6Naf.jpg I'm having trouble with the alignment of the elements. When I use float-start for the image, it aligns properly, but start-0 do ...

Essential Guide to Binding Events with JQuery

Why is the handler for an event on an element triggering the wrong response? I was expecting the click event of Div1 to display a dialog stating 'div1', but it's showing 'div2' instead. I am new to this and trying to figure out wh ...

Guidelines for updating state in React following a delay?

Trying my hand at creating a basic roulette wheel using React, I encountered an issue where setting the state spinning to false at the end of the function did not seem to have any effect. import React, { useState } from "react"; const numbers = ...

Creating a visual selection menu with icon options using jQuery or a similar framework

Currently, I am working on designing an HTML form that includes a field where users must select from a set of options such as sunny, cloudy, rainy, and more. I am seeking a creative alternative to using the <select> or <radio> input elements. ...

On-page refresh triggering HTTP 404 error in Vue3 routing situation

Issue Upon reloading a route, such as /installer, in Vue3.js, I encounter the following error: https://i.sstatic.net/UKxdk.png Code Snippet I am utilizing the Router with the setup below: const router = createRouter({ history: createWebHistory(proces ...