Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle three type images in div as a background images #430

Closed
Riyazkhan1989 opened this issue Dec 24, 2019 · 2 comments
Closed

Handle three type images in div as a background images #430

Riyazkhan1989 opened this issue Dec 24, 2019 · 2 comments

Comments

@Riyazkhan1989
Copy link

Riyazkhan1989 commented Dec 24, 2019

Tjoskar, I am using as background image in
<div class="container tab-inner" [defaultImage]="this.defaultImage" [lazyLoad]="this.image" (onLoad)="myCallbackFunction($event)" [useSrcset]="true">

So I want to handle 3 type images(low, medium, original) in above div background image.

I already have checked it but you are suggesting it using
<picture> <source media="(min-width: {{ screen_lg }})" [attr.defaultImage]="defaultImage" [attr.lazyLoad]="image2"> <source media="(min-width: {{ screen_md }})" [attr.defaultImage]="defaultImage" [attr.lazyLoad]="image3"> <img [defaultImage]="defaultImage" [lazyLoad]="image1"> </picture>
I don't want to use picture tag. I want to do same thing in div tag.

@tjoskar
Copy link
Owner

tjoskar commented Dec 25, 2019

Hi @Riyazkhan1989

It is kind of hard to lazyload a responsive background image for a div, without creating CSS media queries on the fly.

However, you could dynamically set the image by looking at the viewport size. Something like this:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html'
})
export class AppComponent  {
  defaultImage = 'https://via.placeholder.com/16';
  lazyLoadImage = 'https://via.placeholder.com/1280';

  constructor() {
    const screenLg = 1280;
    const screenMd = 960;
    const width = window.innerWidth;

    const image1 = 'https://via.placeholder.com/1280x200';
    const image2 = 'https://via.placeholder.com/960x200';
    const image3 = 'https://via.placeholder.com/200x200';

    if (width >= screenLg) {
      this.lazyLoadImage = image1;
    } else if (width >= screenMd) {
      this.lazyLoadImage = image2;
    } else {
      this.lazyLoadImage = image3;
    }

  }
}

You can se a full example here: https://stackblitz.com/edit/angular-8zlv5n

@tjoskar
Copy link
Owner

tjoskar commented Dec 25, 2019

This will however not work if the user resizes the window.

If you want to support that use case, you will need to listen for resize events.

window.addEventListener('resize', () => {
  this.updateImagePath()
}, true); 

I can elaborate if you want.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants