Strategies for adjusting image components based on various screen sizes

Let's consider a scenario:

There is an image nested inside an introductory div for the desktop layout, like so:

<div class="intro">
            <img id="gambar" src="assets/images/image-intro-desktop.jpg" alt="">
        </div>

Now, when the viewport size changes to mobile, the img tag needs to be updated to:

<img id="gambar" src="assets/images/image-intro-mobile.jpg" alt="">

The question at hand is how to achieve this component change and what JavaScript code is required?

Answer №1

To achieve this effect, utilize CSS styling

<style>
  .introduction{
    background-image: url("assets/images/image-intro-desktop.jpg");
  }

  @media only screen and (max-width: 600px) {
    .introduction{
       background-image: url("assets/images/image-intro-mobile.jpg");
    }
  }
  </style>

  <div class="introduction"></div>

Answer №2

To dynamically change the image source based on window width, you must add event listeners for the resize and load events. Check the window width against your desired breakpoint and update the image source accordingly. If the window width is smaller than the breakpoint, the image source should be changed to a new source. Otherwise, reset the source back to the original.

document.addEventListener( 'resize', changeImageSrc() );
document.addEventListener( 'load', changeImageSrc() );


function changeImageSrc() {
  var init_img_src = document.getElementById('gambar').src;
  
  // Modify the breakpoint value as needed
  if( window.innerWidth < 600 ) {
    document.getElementById('gambar').src = 'https://via.placeholder.com/250';
  } else {
    document.getElementById('gambar').src = init_img_src;
  }
}
<div class="intro">
  <img id="gambar" src="https://via.placeholder.com/550" alt="">
</div>

Answer №3

Here is some JavaScript code for you:

You may consider running this code within a window.onload function depending on your needs.

if(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)){
  // This will return true if the user is on a mobile device
  // You can change the image source here
  document.getElementById('gambar').src = "assets/images/image-intro-mobile.jpg";
}else{
  // This will return false if the user is not on a mobile device
}

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

Enhancing CKEditor: Inserting new elements upon each dialog opening

I am facing a challenge where I need to dynamically add varying numbers of elements to a dialog window each time it is opened. Below is the code I am working with: CKEDITOR.on( 'dialogDefinition', function(ev) { var dialogName = ev.data.name ...

What is the best way to retrieve information from a form that is coded within inner HTML?

I need to extract data from the text fields in my code. How can I do that? Here is my JavaScript function that adds a new form every time the add button is clicked: function elementAppender() { if (count <= 5) { let element = docum ...

Google Web Fonts: Exploring the World of Font Weight Variations

It's quite puzzling as to why the weight of my Google web font in the navigation menu keeps changing on different pages even though I have specifically set it to 700. The CSS for the menu is exactly the same across all pages. Can anyone shed some ligh ...

ReactJS - Unable to access property of undefined object

I encountered a TypeError when rendering, stating that my object is not defined. Despite thinking I defined it before using it. Here is an example of ArticleDetails.js that I am referencing: import React, {Component} from 'react'; class Arti ...

Align text to the right and do not include any images

I am attempting to align the images back to the left under the title, while only floating the description text to the right. I am struggling with clearing the image floats. HTML: <div class="title">System Displays</div> <div class="descrip ...

Issue with collapsing custom-height navigation bar in Bootstrap 4

I have implemented a Bootstrap 4 navbar with a brand logo image sized at 150px x 33px. Now, I want to increase the height of the navbar to 80px. To do this, I added min-height: 80px; in my CSS. <!DOCTYPE html> <html lang="en"> <head> ...

You cannot make a hook call within the body of a function component, unless you are using useNavigate and useEffect in conjunction with axios interceptors

Currently, I am delving into React and attempting to include a Bearer token for private API calls. My approach involves writing a private axios function to intercept requests and responses. Subsequently, I invoke it in my API.js file to fetch data from the ...

Unable to retrieve observable modifications

In my code file for handling reports, named report.service.ts, I have a method that retrieves reports data. This method simply returns a constant array of report objects from a mock source. Here is the implementation: @Injectable() export class ReportServ ...

Unable to fulfill all the promises in JavaScript

As I develop a filter feature, I have categories and cities in the format: ['New York'], ['Cars']. The goal is to iterate through them to retrieve products based on each city or category. My approach involves storing these products in t ...

Creating an Array in AngularJS with ng-model and submitting it with jQuery: A comprehensive guide

I am struggling to submit an array of values using jQuery and AngularJS. Whenever I click the submit button, only the first array value is being retrieved. How can I get all array values using ng-model? Here is a link to all my code: https://jsfiddle.net/r ...

Utilizing adapter headers in contexts other than ActiveModelAdapter

I have successfully implemented my authorization system with Ember Data. All my ember-data calls are secure and signed correctly using adapter.ajax() instead of $.ajax. However, I am facing a situation where I need to utilize a third-party upload library t ...

How to efficiently eliminate multiple entries with SREM in ioredis?

I am curious about the proper syntax for removing multiple entries using the SREM command. When I try this: const myKey = "myKey"; const entriesToRemove: string[] = ... this.redisClient.srem(myKey, entriesToRemove); I end up with: ReplyError: ...

Guide on transferring data from an API using mapped React hooks

I am working with react hooks and attempting to pass a value to the delete function and execute the put function <Fab aria-label="delete" className={classes.fab} value={vacation.id} ...

Attempting to showcase information on the Angular frontend

When attempting to retrieve the Street name, I am seeing [object Object]. What is the optimal approach for displaying JSON data on the client side? I managed to display a street name but struggled with other components. How can I access the other elements ...

Uncaught ReferenceError: jQuery is undefined" - Navigating the Angular and JavaScript Realm with

There is an Angular project that I am working on, and it utilizes the AvayaClientSDK consisting of three JavaScript files. While trying to import the AvayaClientSDK JS file into my component, an error message stating "jQuery is not defined" appeared. ...

AngularJS: when only one line is visible, the other remains hidden

Issue with AngularJS: Only One Line Displaying Instead of Both I am encountering an issue with my AngularJS code where only one of the elements is displaying on my page. function Today($scope, $timeout) { $scope.now_time = 0; (function update() { ...

What could be causing my bounce animation to begin 50 pixels higher than its intended starting point?

Trying to create a bouncing effect on text Check out my attempt here. It seems like the bug is in this area. @keyframes bounce{ 0%, 40%{ transform:scale(2,.5) translate(0,100px); } 45%,55%{ transform:translate(0,-50px); } 55%, 100%{ ...

Utilizing a distinct template with ui-router: A step-by-step guide

I am currently working on an Angular application that utilizes ui-router for view routing. Within my master template, I have all the layout elements set up, including my ui-view as shown below: <div class="content" ui-view> <div> Here are my ...

Exploring the power of hierarchical organization in node.js modules

One of my modules is called UserProvider and it has the following structure: var UserProvider = function(db) { ... } UserProvider.prototype.createUser = function(email, password, callback) { ... } UserProvider.prototype.findUserByEmail = function(email, c ...

What is preventing the Navbar from aligning to the right side in Bootstrap 5?

I'm trying to position only the "Account" navbar all the way on the right side using ms-auto, but it doesn't seem to be working correctly. Here's my code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="u ...