Change the positioning of the image to a new column within the bootstrap grid when a

My website utilizes Bootstrap 4, featuring a <container> with two individual columns.

For screen sizes within the Bootstrap 4 breakpoints of md-xl, these columns are displayed side by side with equal widths: col-md-6. On smaller screens like sm-xs, they stack into a single column: col-xs-12.

The goal here is to rearrange the blue img above the red img specifically on md sized screens. I've experimented with some JavaScript and Node.insertBefore(), but my preference is to achieve this using CSS in Bootstrap 4.

https://i.sstatic.net/P1nVA.png

Below is an initial attempt I made with basic JavaScript - Can someone guide me in the right direction?


           function movelogo() {
                var logo = document.getElementById('logo');
                logo.insertBefore(logo, 'next_col');
            }

            window.addEventListener('resize', movelogo);
        

            <!DOCTYPE html>
            <html lang="en">
                <head>
                    <meta charset="UTF-8">
                    <meta http-equiv="X-UA-Compatible" content="IE=edge">
                    <meta name="viewport" content="width=device-width, initial-scale=1 viewport-fit=cover">
                    <meta http-equiv="content-type" content="text/html"/>
                    <title>Title</title>
                    
                    <!-- Bootstrap CSS -->
                    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
                          integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
                          
                    <!-- Font Awesome CSS -->
                    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css"
                          integrity="sha384-mzrmE5qonljUremFsqc01SB46JvROS7bZs3IO2EmfFsd15uHvIt+Y8vEf7N7fWAU" crossorigin="anonymous">

                    <!-- Custom CSS -->
                    <link rel="stylesheet" type="text/css" href="css/main.css">
                 </head>
                 
                 <body>
                    <div id="about" class="container">
                        <h1 class="text-center display-3 mb-4">About</h1>
                        <div class="row justify-content-center">
                             
                            <div class="col-xs-12 col-md-6">
                                <img src="https://via.placeholder.com/300/0000FF/808080?text=Logo" class="img-fluid mb-5 mx-auto d-block" id="logo" alt="Logo">
                                     <p>Placeholder text...</p>
                                 </div>
                                 
                                 <div class="col-xs-12 col-md-6" id="next_col">
                                     <img src="https://via.placeholder.com/400x600/FF0000/FFFFFF?text=Image" alt="Main image" class="mx-auto d-block img-fluid">
                                  </div>
                             </div>
                         </div>
                         
                     <!-- Optional JavaScript-->
                        <!--[jQuery first, then Popper.js, then Bootstrap JS]-->
                        <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
                        
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>

<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
</body>
</html>

Answer №1

Learn how to utilize Media Queries with JavaScript in a simple way without altering your HTML structure. Just add an id="current_col" to your logo div.

(Check out the result below using sm-6 in the snippet)

function resize(x) {
  if (x.matches) { // If media query matches
    document.getElementById('next_col').prepend(
      document.getElementById('logo')
    );
  } else {
    if ($("#next_col").children("#logo").length > 0) {
      document.getElementById('current_col').prepend(
        document.getElementById('logo')
      );
    }
  }
}

var x = window.matchMedia("(max-width: 960px)")
resize(x) // Call listener function at run time
x.addListener(resize) // Attach listener function on state changes
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8>
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1 viewport-fit=cover">
  <meta http-equiv="content-type" content="text/html" />
  <title>Title</title>

  <!-- Bootstrap CSS -->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

  <!-- Font Awesome CSS -->
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css" integrity="sha384-mzrmE5qonljUremFsqc01SB46JvROS7bZs3IO2EmfFsd15uHvIt+Y8vEf7N7fWAU" crossorigin="anonymous">

  <!-- Custom CSS -->
  <link rel="stylesheet" type="text/css" href="css/main.css">

</head>

<body>

  <div id="about" class="container">
    <h1 class="text-center display-3 mb-4">About</h1>
    <div class="row justify-content-center">

      <div class="col-xs-12 col-sm-6" id="current_col">

        <img src="https://via.placeholder.com/300/0000FF/808080?text=Logo" class="img-fluid mb-5 mx-auto d-block" id="logo" alt="Logo">

        <p>Metuentes igitur idem latrones Lycaoniam magna parte campestrem cum se inpares nostris fore congressione stataria documentis frequentibus scirent, tramitibus deviis petivere Pamphyliam diu quidem intactam sed timore populationum et caedium, milite
          per omnia diffuso propinqua, magnis undique praesidiis conmunitam.
        </p>

        <p> Quid enim tam absurdum quam delectari multis inanimis rebus, ut honore, ut gloria, ut aedificio, ut vestitu cultuque corporis, animante virtute praedito, eo qui vel amare vel, ut ita dicam, redamare possit, non admodum delectari? Nihil est enim
          remuneratione benevolentiae, nihil vicissitudine studiorum officiorumque iucundius.</p>
      </div>

      <div class="col-xs-12 col-sm-6" id="next_col">
        <img src="https://via.placeholder.com/400x600/FF0000/FFFFFF?text=Image" alt="Main image" class="mx-auto d-block img-fluid">
      </div>
    </div>
  </div>


  <!-- Optional JavaScript -->
  <!-- jQuery first, then Popper.js, then Bootstrap JS -->
  <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
</body>

</html>

Test it out here : https://jsfiddle.net/748sormv/

Answer №2

Some issues have been identified...

  • next_col is currently a string and not a Node.

  • The usage of

    logo.insertBefore(logo, 'next_col');
    is an attempt to insert the logo into itself before next_col, which does not exist within the logo element.

"The code below tries to relocate the logo on any screen size (the detection of the screen size can be addressed later)." 😞

This implies that each time the window resize event occurs, it will trigger the insertBefore function, potentially causing the browser to crash. A conditional test is required, as well as addressing the other identified issues....

function movelogo() {
    var logo = document.getElementById('logo');
    var next_col = document.getElementById('next_col');
    if (logo.parentNode !== next_col) {
        next_col.insertBefore(logo, next_col.childNodes[0]);
    }
}


However, utilizing Bootstrap's responsiveness eliminates the need for JS to alter the layout on xs and sm screen widths:

Answer №3

If you want to solve this issue, try expanding the view to full size and then resizing the window to a width below 480px to observe the outcome. I made use of a media query to address your concern. Additionally, I introduced two new enclosing divs in your HTML, namely bluecol and redcol.

The bluecol div encapsulates the blue image along with its accompanying text. Within the media query, I included float:left for the text div to ensure it aligns to the left upon resize. Initially, I had placed the text div after the image in the code, resulting in the text displaying first on larger screens. To achieve the desired result, I eliminated some of the inline Bootstrap CSS and incorporated some newly created (brief) custom classes.

I hope this explanation proves helpful.

h1 {
  text-align: center;
  padding: 10px;
}

#abouttxt {
  font-weight: normal;
  font-size: 10pt;
  line-height:1.4em;
  margin-top:12px;
  
}

#logo {
  width: 60%;
  margin: 0 20%;
}

#abouttxt,
#logo {
  display: inline-block;
}
.red {
  width: 80%;
  margin: 0 10%;
}

#bluecol,
#redcol {
  display: block;
}

@media only screen and (min-width:480px) {
  #abouttxt {
    max-width: 50%;
    float: left;
  }
  #logo {
    max-width: 40%;
    margin: 5px 10px;
  }
  #abouttxt,
  #logo {
    display: inline-block;
    vertical-align: top;
  }
  .red {
    width: 40%;
    margin-left: 52%;
  }
  #bluecol,
  #redcol {
    display: inline-block;
  }
}
<!DOCTYPE html>

<html lang="en">

... (HTML content continues here) ... </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

Implementing a click event to convert text to input in Angular 5

I'm struggling with setting values instead of just getting them. I want to switch from using divs to input fields and update the values when in "editMode". <div class="geim__sets"> <div *ngFor="let set of game.sets" class="geim__set"> ...

Comparing adjust-leading-to with leader in Compass - what sets them apart?

Currently exploring Compass and feeling a bit puzzled about the functionality of two mixins: adjust-leading-to and leader. Would appreciate it if someone could clarify the distinction between them. ...

How can I delete an individual HTML element that does not have a class or ID?

I am currently working with a theme that cannot be altered due to automatic update requirements. The theme includes the following HTML code snippet: <div class="dropdown-menu"> <a href="#">Profile</a> | <a href="#">Logout</a> ...

Using Vue's v-if statement to determine if a variable is either empty or null

Using a v-if statement to display certain HTML only if the archiveNote variable is not empty or null. <div v-if="archiveNote === null || archiveNote ===''" class="form-check ml-3" id="include-note-div"> Here is how it's implemented ...

Dealing with the response data from $http request in AngularJS

Below is the client-side code written in AngularJS (which is functioning properly): $scope.ajaxLogin = function(){ var fn = document.getElementById("username").value; var pw = document.getElementById("password").value; $http({ url: "my ...

Creating an infinite scroll with a gradient background: a step-by-step guide

I am currently working on a project to develop an infinite scrolling webpage with a dynamic gradient background that changes based on the user's scroll position. While researching, I came across some code for infinite scrolling using time and date. I ...

Getting latitude and longitude from Google Maps in a React Native appHere are the steps to

Looking to retrieve the latitude and longitude from Google using React Native. As a newcomer to React Native, I have been unable to find any resources to address this issue. Any assistance would be greatly appreciated. Thanks! Thanks ...

Is it feasible to utilize a Heroku Node server solely for serving basic HTML pages?

Is there a way to simply upload multiple HTML (or any) files and access them via URL without having to define routes, set up static files, etc.? I am using a NodeJS/ExpressJS app and would like to serve certain files and folders as regular HTML pages. ...

Tips for extracting only a portion of the JavaScript timestamp

I have a JavaScript timestamp that reads Tue Sep 30 2014 12:02:50 GMT-0400 (EDT). When I use the .getTime() method, I get 1412092970.768 Typically, this timestamp represents a specific time of today. My question is whether it's possible to extract o ...

Exploring the capabilities of TabrisJs in conjunction with Upnp technology

Working with Upnp in TabrisJs seems to be a bit challenging. Even though it has good support for node packages, I am facing difficulties while dealing with Upnp. I included node-upnp-client in my package.json file. "dependencies": { "tabris": "^2.0 ...

What is the proper way to utilize the JavaScript String.replace() function?

Below is the HTML code snippet containing placeholder text: <p style="padding: 3%; border:1px solid black" id="myspan" ng-model="myspan" ng-mouseup="showSelectedText()"> And so our resident genius, our Dr. Jekyll, explosively completed his trans ...

Add data to a JSON structure

I'm attempting to populate the screenshot object with all PNG files in the following code: common.getFilesInFolder(reportDir, '.png', function(err, PNGs) { if(!err && PNGs.length > 0){ for(var i=0; i< PNGs.le ...

Issue with displaying Git remote repository on list item element (ul) not appearing

My attempt to showcase my GitHub repositories via their API is not displaying on my webpage, even though the exact same code works perfectly fine here on JSFiddle Upon debugging, it seems that the script is being invoked but the content is not loading wit ...

Select dates within a range using jQuery UI datepicker

Looking to implement the jQuery UI datepicker on my asp.net aspx page, I aim to enable range selection and include an OK button on the calendar. After discovering a tutorial demonstrating this functionality at the following link: jQuery UI Datepicker - Ra ...

The object's texture remains static and does not follow its rotation

My simple object has a texture drawn onto it using a shader. Everything is working correctly, except when I rotate the object, the texture does not rotate along with it. Instead, it seems to remain in a 2D space, creating the 'mask' effect shown ...

Convert an array comprising arrays/objects into JSON format

This problem is really challenging for me. The structure of my array goes like this: array1 = [ [array2], [array3], [array4] ... [array17] ] array2 = [ ['obj1'], ['obj2'], ['obj3'] ... ['obj30'] ] ... ... obj1 = ({p ...

The Ajax call failed to connect with the matching JSON file

<!DOCTYPE html> <html> <body> <p id="demo"></p> <script <script> function launch_program(){ var xml=new XMLHttpRequest(); var url="student.json"; xml.open("GET", url, true); xml.send(); xml.onreadystatechange=fun ...

What is the process of using the split() method to extract specific text from a string in JavaScript?

Working with AngularJS and facing a requirement to extract a specific text from a scope value. Here's my scope value: $scope.myLogMsg = '1111 order is placed by Sukumar Ms(User)'; //output: by Sukumar Ms(User) Desired output: by Sukumar Ms ...

Pass the html form data to a PHP variable

I need assistance with updating a PHP variable with the value of an HTML form submission. Here is the code snippet: <form action="callback2.php" method="POST"> Enter Phone Number: <input type="text" size="10" name="nummerb" id="nummerb"> <i ...

Creating a promise in an AngularJS factory function to perform an operation

When working within an Angular factory, I am tasked with creating a function that must return a promise. Once the promise is returned, additional functionality will be added. SPApp.factory('processing', ['$http', '$rootScope&a ...