Discovering and exchanging two div elements using jQuery

Currently tackling a responsive website design. When the screen is resized to mobile view, I must reorganize some div elements. Currently, here's how I'm handling it:

$(window).resize(function() {
  var width = $(window).width();
  if( width < 768) {
    $('#id-1 .image-box').insertBefore($('#id-1 .text-box'));
    $('#id-2 .image-box').insertBefore($('#id-1 .text-box'));
    $('#id-3 .image-box').insertBefore($('#id-1 .text-box'));
  } else if( width > 767) {
    $('#id-1 .text-box').insertBefore($('#id-1 .image-box'));
    $('#id-2 .text-box').insertBefore($('#id-2 .image-box'));
    $('#id-3 .text-box').insertBefore($('#id-3 .image-box'));
  }
} );
$(window).resize();

Is there a more effective approach for achieving this? I aim to locate a specific div with the class '.image-box', verify the preceding div's class, and if it's '.text-box', interchange their positions.

Your insights are greatly appreciated!

Answer №1

Here's a more dynamic approach to handle the HTML content.

const elements = [
   $('#element-1'),
   $('#element-2'),
   $('#element-3')
];
const switchElements = function(firstSelector, secondSelector) {
    for ( let i = 0; i < elements.length; ++i ) {
        elements[i].find(firstSelector)
            .insertBefore(elements[i].find(secondSelector));
    }
};
$(window).resize(function() {
  const screenWidth = $(window).width();
  if( screenWidth < 768) {
    switchElements('.image-container', '.text-container');
  } else if( screenWidth > 767) {
    switchElements('.text-container', '.image-container');
  }
});
$(window).resize();

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

Partial view could not be loaded through ajax request

I am trying to dynamically load data from a partial view into a div when a hyperlink is clicked. However, despite writing code to call an action that returns the partial view, I am having trouble actually loading it. Below is my Index.cshtml code: @mode ...

Add a div inside the labels to serve as additional explanatory text. This div should be included within each radio group and its

Link to Fiddle I'm looking to dynamically append a div containing helper text inside each label of a radio button group, within its wrapper div. Since my radio button group code is generated dynamically, adding static helper text to labels using HTM ...

HTML links have been disabled

I have been making updates to the charity website I manage, heroinitiative.org. You can view the revamp progress here: (please note that this is not live code, it is simply for my boss to see the progress and does not need to be kept secret, hence why I a ...

response from jquery when condition is met

Currently, I am utilizing jquery-ajax to transmit data to a PHP file. Once the transmission is complete, the PHP responds back. In this case, everything is running smoothly. However, I'm faced with uncertainty regarding how to implement an if statemen ...

Update the identifiers and titles for duplicated elements

On my form, users can input multiple delegate details. Here's a snippet of the HTML code: <div id="Delegate1" class="clonedInput"> <h4 id="reference" name="reference" class="heading-reference">Delegate #1</h4> ...

Using percentages to convert CSS transforms from pixels is ineffective

Here is the code snippet I am currently working with: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <div style="width:50%;height:30%;background:#65 ...

Guide to updating Form Action on Form Submission with JQuery Ajax Request

When attempting to update and delete rows, I am encountering an issue with the persistence of the action URL in my jQuery AJAX functions. I have separate functions for update and delete operations, each with a different action URL. However, when I try to ...

Exploring the differences between two CSS style attributes using JQuery

Can someone help me with a quick question about CSS? I need to compare two style attributes, specifically margin-left. If the margin-left is less than 500px, I don't want to make any changes. However, if it's greater than 500px, I want to add ano ...

What could be causing the issue: Unable to locate or read the file: ./styles-variables?

I'm currently following a tutorial on how to create responsive layouts with Bootstrap 4 and Angular 6. You can find the tutorial here. I've reached a point where I need to import styles-variables.scss in my styles file, but I keep encountering t ...

Elements floating in space, stretching across the entire width

In my design, I have a fixed size layout with a centered content container. My goal is to have the menu (home, about, contact, login) span 100% of the screen width. You can view the current setup in this jsfiddle: http://jsfiddle.net/Hxhc5/1/ I am aimin ...

Stopping PHP execution when an Ajax request is aborted

I want the browser to wait for notifications, but stop waiting if a link is clicked. To achieve this, I have created a PHP script with a while loop that ends when an event occurs and then returns that event. PHP require 'required.php'; ignore_ ...

Is it necessary to re-specify the parent when using the not selector?

How can I select (n+2) rows from a table excluding the 4th row using jQuery? Which of the following jQuery selectors is correct for this task? $("#table_id tr:nth-child(n+2)").not("tr:nth-child(4)") OR $("#table_id tr:nth-child(n+2)").not("#table_id tr ...

Is there a way to switch the sorting order on a Bootstrap page using a button without having to refresh the page?

I'm currently working on a template for an app that already exists and would like to add a button to change the sort order of displayed elements on a webpage. The page is styled using Bootstrap 5.3, so I have access to jQuery and other Bootstrap featu ...

Steps to create a conditional AJAX request triggered by the onbeforeload event depending on the value of a variable

My website script tracks user login status in real time using "onbeforeunload", ajax, and logout.php. This method updates the MySQL database with a value of 1 or 0 to indicate if a user is logged in. Unlike monitoring cookies, this approach allows accurate ...

How to replicate a WordPress menu bar

Embarking on my coding journey, I've completed courses in HTML, PHP, CSS, JavaScript, and MySQL. Now, I've decided to dive into hands-on learning by creating a Wordpress child theme. My current challenge is figuring out how to overlay two differ ...

How can we achieve the same functionality as React Native's { flex: 1 } in React JS?

I've been diving into React Native development, and now I'm exploring React.js for web applications. However, I'm facing a challenge in creating a simple View that takes up the entire screen to begin experimenting with different components. ...

Steps to insert an HTML tag with jQuery

Below is a function I have written to display AJAX response in HTML: function loadData() { $.ajax({ type: "post", url: "http://127.0.0.1/get_scroll_rec/", cache: false, data:'&apo ...

Launch a new window to display a PDF file using an Ajax request

Currently, I am in the process of developing a web application which utilizes nodejs and jquery. One specific feature requires a reporting component. When a user transmits data to the server via an ajax call (I opt for the 'get' method for simpli ...

Discovering the flaw in my programming that pertains to JSON parsing

After countless hours of searching and reviewing documentation, I am still unable to identify the issue with my jQuery code. My goal is to practice reading a local JSON file and displaying its contents in the body of my HTML document. $(document).ready(fu ...

Transforming a curl command into an AJAX request

Can someone help me with using an API by inputting a curl command through AJAX? Any guidance is greatly appreciated. Here is the curl command I am struggling with: curl -H “Authorization: Token #{auth_token}” -X GET http://localhost:3000/api/v1/basket ...