Change image according to screen resolution

Asked

Viewed 573 times

1

I’m studying something in jQuery in case. It is possible to change an image according to the screen resolution?

For example: in the browser itself, with it without minimizing is the big image. If minimize, the function switches to the small image.

2 answers

2

Yes, it is possible! You can do it using the method .width()

Description: THE .width() gets the current width calculated for the first element in the set of corresponding elements pointed.

In this case the corresponding element pointed out will be the window, to get the width of the window/viewport:

$(window).width()

Then we will calculate whether or not the width of the viewport is greater than a value we want to determine, for example:

if ($(window).width() > 500) {
   alert('A largura da janela é menor que 500');
} else {
   alert('A largura da janela é maior que 500');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

Here you have a example in jsFiddle to see this code in action. Drag the edges of the results section by decreasing or increasing the window size to see the image changing.

0

You can place a call to your function within the $(window).resize(function() { ... });. I suggest using document.body.scrollWidth instead of $(window).width() because the first takes the width from inside the screen by unchecking the scrollbar, browser border, etc.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.