A javascript function that will switch different image source or background source for a single breakpoint or device width.
Download the js file or pull it on your local folder. Add it on your script folder and declare it on your main script file.
Switcher works by initializing it and then adding the .js-switcher class on your element and its custom dataset.
window.addEventListener('load', function () {
switcher.init();
});
<img class='js-switcher'>
<div class='js-switcher'></div>
the init function have 2 parameters, onresize and debounceTimer
- onresize (boolean) - trigger the switcher when the window has been resize. The default value is true.
- debounceTimer (number) - trigger the switcher after a certain seconds after the window has been resize. The value is represented on millisecond. The default value is 500(ms).
switcher.init(false, 1000);
- data-breakpoint - by adding this dataset, it will detect the breakpoint on when to switch the image source of your element. Its value will be represented on pixel.
<img class='js-switcher' data-breakpoint='900'>
<div class='js-switcher' data-breakpoint='900'></div>
- data-largeImage - this dataset will be the image source greater than the value of breakpoint.
<img class='js-switcher' data-breakpoint='900' data-largeImage='image/desktop.png'>
<div class='js-switcher' data-breakpoint='900' data-largeImage='image/desktop.png'></div>
- data-smallImage - this dataset will be the image source less than the value of breakpoint.
<img class='js-switcher' data-breakpoint='900' data-largeImage='image/desktop.png' data-smallImage='image/mobile.png'>
<div class='js-switcher' data-breakpoint='900' data-largeImage='image/desktop.png' data-smallImage='image/mobile.png'></div>