Exhibition of items arranged in a floating manner. I am looking to insert a new class within the layout using jquery

Let's dive into a bit more detail. I have a gallery with 9 elements aligned to the left, creating 3 elements per line as shown below:

    1   2   3 <--line 1

    4   5   6 <--line 2

    7   8   9 <--line 3

What I am attempting to do is when any element is clicked, I want to add a div below the line it belongs to. For instance, if I click on element 2, it should add a div after the 3rd element between line 1 and 2.

I've tried selecting all the 3rd elements of each line using :nth-child, but I'm struggling to make jQuery comprehend which line it is on. Frankly, I'm baffled about how to tackle this issue.

Any insights or suggestions would be greatly appreciated. Thank you, Constantin Chirila

Later edit: I apologize for the messy code; it's part of a larger project.

              <a href="#" class="dealer--item" data="hongkong">
                        <h4 class="dealer--item-title">Hong Kong</h4>
                    </a>

                    <a href="#" class="dealer--item" data="australia">
                        <h4 class="dealer--item-title">Sweden</h4>
                    </a>

                    <a href="#" class="dealer--item" data="sweden">
                        <h4 class="dealer--item-title">Sweden</h4>
                    </a>
                    
                    etc...
                </div>

Jquery:

$(".dealer--item").click(function (e) {
    var idSelector = $(this).attr('data');

    e.preventDefault();
    $('.dealer--item').not(this).removeClass('is-selected');
    $(this).toggleClass("is-selected");

    $(".dealer--item:nth-child(3n)").each(function (index) {
        $(this).addClass("foo" + index);
    });

    $('foo0').after($('#' + idSelector)) //this is where i lost it as its not working for other 6 elements

    $('#' + idSelector).fadeToggle(300);
});

And here is the content that needs to be added between the lines based on the clicked element:

<div class="dealer--address" id="australia">
Address here
</div>
<div class="dealer--address" id="hongkong">
Address here
</div>
<div class="dealer--address" id="sweden">
Address here
</div>
        
etc...

Answer №1

One idea to enhance your layout is by incorporating an additional div beneath the floated elements on the left. Initially, you can hide this div using display:none; and then reveal it using jQuery when clicked.

$("#clickable-item").click(function(){
    $("#element-to-reveal").show();
});

Personally, I prefer utilizing jQuery for all my click and display actions. It provides a cleaner approach in handling these functionalities.

Answer №2

<!DOCTYPE html>
<html>

<head>
    <title>Testing HTML Page</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
    <style type="text/css">
        .floating {
            float: left;
            width: 30%;
            margin: 1%;
            height: 100px;
            background: #ffe4c4;
        }

        .Content {
            display:none;       
            width: 100%;
            background: green;
        }

        #contentOnDisplay {
            min-height: 100px;
            width: 100%;
            float: left; 
            background: green;
            display: block;
        }
    </style>
</head>

<body>
    <div class="Content" id="floatContent1">Sample Content 1</div>
    <div class="Content" id="floatContent2">Sample Content 2</div>
    <div class="Content" id="floatContent3">Sample Content 3</div>
    <div class="Content" id="floatContent4">Sample Content 4</div>
    <div class="Content" id="floatContent5">Sample Content 5</div>
    <div class="Content" id="floatContent6">Sample Content 6</div>
    <div class="Content" id="floatContent7">Sample Content 7</div>
<!--    <div class="Content" id="floatContent8">Sample Content 8</div>
    <div class="Content" id="floatContent9">Sample Content 9</div>-->

    <div class="floating" id="float1"></div>
    <div class="floating" id="float2"></div>
    <div class="floating" id="float3"></div>
    <div class="floating" id="float4"></div>
    <div class="floating" id="float5"></div>
    <div class="floating" id="float6"></div>
    <div class="floating" id="float7"></div>
<!--    <div class="floating" id="float8"></div>
    <div class="floating" id="float9"></div>-->

<script type="text/javascript">
    var getLeftMostPositionOfFirstItem = $("#float1").position().left;

    $(document).ready(function() {
        $(".floating").click(function() {
            var elementID = $(this).attr("id");
            $("#contentOnDisplay").remove(); //hides the existing contents
            var firstItemOFNextRow = getNextRowFirstItem(elementID);

            getAllContentsAndPrepend(firstItemOFNextRow, getNextRowFirstItemId(elementID));
            return false;
        });
    });

    function getNextRowFirstItem(clickedItemID) {
        var thisItemNumber = parseInt(clickedItemID.replace("float", ""));
        var position = $("#" + clickedItemID).position();
        var IdToInsertBefore = "";
        for (var i = thisItemNumber + 1; i < $(".floating").length; i++) {
            var leftPostitonOfThisItem = $("#float" + i).position().left;
            if (leftPostitonOfThisItem < getLeftMostPositionOfFirstItem*1.5) {
                IdToInsertBefore = "#float" + i;
                break;
            }
        }
        if (IdToInsertBefore.length == "") {
            IdToInsertBefore = "#float" + $(".floating").length;
        }
        return IdToInsertBefore;
    };

    function getNextRowFirstItemId(elementID) {
        return parseInt(elementID.replace("float", ""));
    };

    function getAllContentsAndPrepend(idToPrepend, IdNumber) {
        var contentHtml = $("#float" + IdNumber + "Content").html();
        contentHtml = "<div id='contentOnDisplay'>" + contentHtml + "</div>";
        if (IdNumber <= $(".floating").length - getLastRowItemsCount()) {
            $(idToPrepend).before(contentHtml);
        } else {
            $(idToPrepend).after(contentHtml);
        }
        return false;
    };

    function getLastRowItemsCount() {
        var numberOfColoumns = 0;
        for (var i = $(".floating").length; i > 0; i--) {
            var leftPostitonOfThisItem = $("#float" + i).position().left;
            numberOfColoumns++;
            if (leftPostitonOfThisItem < getLeftMostPositionOfFirstItem * 1.5) { 
                break;
            }
        }
        return numberOfColoumns;
    };
</script>
</body>
</html>

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

Understanding the Relationship Between Interfaces and Classes in Typescript

I’ve come across an interesting issue while working on a TypeScript project (version 2.9.2) involving unexpected polymorphic behavior. In languages like Java and C#, both classes and interfaces contribute to defining polymorphic behaviors. For example, i ...

Locating elements with Selenium Webdriver using xpath

<a style="color:White;" href="javascript:__doPostBack('dnn$ctr674$Case$gvCaseSearchDetails','Page$777')">777</a> Can anyone help with writing an xpath for the HTML code above? The goal is to locate elements using the identi ...

Having trouble with Node integration in Electron?

In my inventory application, I have the backend written in Python 3.7 and I am using Electron to create a GUI for it. To communicate with the Python code, I am utilizing the Node.js Module "python-shell" and would like to keep all of its code in a separate ...

Ways to eliminate all jQuery events (or avoid reinitializing multiple times)

As I work on building a web page using AJAX, I have encountered an issue with setting up click events. One particular button on the page allows users to exit and return to their previous location. However, each time the user rebuilds the same div and sets ...

Problems with the Chosen property of MenuItem within Material-UI

The MenuItem's "selected" property does not seem to be functioning correctly within the Select component. For reference, please visit https://codesandbox.io/s/9j8z661lny I have attempted to use comparison with the Id, and even tried using selected={t ...

Is it advisable to specify data types for my JSON data in TypeScript?

For the shopping application in my project, I am utilizing a JSON structure to categorize products as either hot or branded. However, I encountered an issue when trying to define a type for the entire JSON object labeled "full". Despite my attempts, it app ...

Angular Directive Fails to Execute Within ng-repeat Loop

In my current configuration, I have: App/Directive var app = angular.module("MyApp", []); app.directive("adminRosterItem", function () { return { restrict: "E", scope: { displayText: "@" }, template: "< ...

How can I include multiple dictionary entries in a JSON file at once?

After attempting to include an array with dictionaries in a JSON file, I encountered multiple errors. This has led me to question whether it is feasible to add dictionaries directly into a JSON file without using Node.JS for data insertion. Here is an exa ...

The THREE.WebGLProgram encountered a shader error: gl.getProgramInfoLog indicates that a compiled fragment shader must be attached

I'm currently working on visualizing particles and adjusting their appearance using shaders. It may seem like a simple task, but I've encountered a problem that's throwing me off... The error message includes some code, but I'm finding ...

Ways to center vertically aligned buttons within cards in a React application with Material-UI

I've encountered an issue with my ReactJS project using material-ui. I created 3 cards, each with a paragraph of varying lengths. This caused the buttons to be misaligned vertically in each card, as the position differs due to paragraph size differenc ...

JavaScript objects and AJAX versus ASP MVC3 Model: A comparison of client-side and server

As someone who is still learning about MVC, I find myself a bit unsure about the best way to integrate MVC models with JavaScript objects and AJAX. For instance, in one of my applications, I have a calendar that displays user events stored in a database. ...

Implementing state management with Vue.js

After creating a login page and setting conditions to display different NAVBARs based on the user's login status, I encountered an issue where the rendering seemed to be delayed. In the login process, I utilized local storage to store a token for auth ...

Using Jquery in asp.net to dynamically add and delete rows within a table

Having an organized table on the Master Page table border="1" border-style="dashed" width="80%" id="tblAddBirthdays" tr id="tr" td asp:TextBox ID="txFirstName" runat="server" asp:TextBox asp:TextBox I ...

Is it possible to spice up functions passed as @Input in Angular with curry?

I have a set of modals with similar styling but completely different functionalities that I need to use in various scenarios within my app. To make it easier for me, I want to pass the logic as input in these different scenarios. When using simple function ...

Issue encountered when displaying an organized list in next.js

I have been working on rendering an array of items in descending order based on their values. Everything seems to be functioning correctly, but I keep encountering an error that reads Error: Text content does not match server-rendered HTML. whenever I tr ...

Is there a way to fill select boxes with multiple values?

As I set up a jqGrid, I encountered the challenge of visualizing multiple values in one cell. The data is sourced from a form where users can select multiple options. While I managed to display the select box, I struggled with populating it. My attempts to ...

Alter the class generated by ng-repeat with a click

I currently have a dynamically generated menu displayed on my website, and I am looking to apply a specific class to the active menu item based on the URL (using ngRoutes). The menu items are generated from a $scope.menu object, so my initial thought was t ...

Learn how to easily center a responsive navbar using Twitter Bootstrap

I'm having a bit of trouble creating a website with Twitter Bootstrap, specifically when it comes to centering the navigation links in responsive design. My goal is to have a two-row navigation bar for tablet and phone devices, with the brand name at ...

The click event fails to trigger when a <tr> element is dynamically appended via jQuery ajax

Hi there, I'm encountering an issue with the click event of jQuery. In my ajax function, I am dynamically adding a table row that includes a button with the class btn btn-default getEditCategory, but unfortunately, it is not working as expected. Belo ...

Learn the process of sending code to a database using AJAX

I am facing a challenge in saving HTML and Javascript codes to a Database using Ajax. I am unsure about the optimal way to do this. Writing all the codes as Strings for the variable seems cumbersome. Do you have any suggestions to simplify this process? & ...