I'm working on something and I'm trying to add and remove elements based on the browser width. In the example that I have ( https://jsfiddle.net/swpm3aL1/ ), I want the image to appear when browser width is 700px or lower and remove the video, and vise versa.
I have some code but it's not working. What am I doing wrong?
Thank you for your time and help!
if ($(window).width() > 700) {
$('body').remove('#image');
$('body').add('#video');
} else {
$('body').remove('#video');
$('body').add('#image');
}
You clearly didn't RTFM
if ($(window).width() > 700) {
$('#image').hide();
$('#video').show();
} else {
$('#image').show();
$('#video').hide();
}
The jQuery manual, or the jsFiddle manual https://jsfiddle.net/swpm3aL1/1/
If you want this on window resize
$(window).on('resize', function(){
if ($(window).width() > 700) {
$('#image').hide();
$('#video').show();
} else {
$('#image').show();
$('#video').hide();
}
}).trigger('resize'); // <-- and trigger so it works on page load
If you want to handle onload, resize and change of orientation, then following code will be handy:
$(window).on("orientationchange load resize", function () {
if ($(window).width() > 700) {
$('#image').hide();
$('#video').show();
} else {
$('#image').show();
$('#video').hide();
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.