I need to make a p tag visible or invisible into my html depending on the size of the width device.
The fastest solution is to give two different classes like “desktop” and “mobile” and make them displayed into block or none depending on media query.
The problem with this solution is that the text is into html twice, so for my SEO this is a problem: so, I create a little function, using .append, .appendTo aand finally .insertAfter, to insert my text into specific divs, but with no happy ending: https://jsfiddle.net/noemi84/rej5av6y/
<div class="main-image-block">
</div>
<div class="home-main-text">
</div>
<script>
function resize() {
if (jQuery(window).width() < 934) {
jQuery('<p>example text</p>').insertAfter('.main-image-block');
} else {
jQuery('<p>bottom text</p>').insertAfter('.home-main-text');
}
}
resize();
jQuery(document).ready(function($) {
$(window).on('resize', resize);
});
</script>
The p tag is duplicated again and again, but I want it once; I want also to have this resize active on the page, so, if a user resize the window he will never see two text but only the one depending on the actual window sizes.
Thanks a lot 🙂
4
Answers
There’s no need for JS code here as you can achieve what you need using CSS media queries.
Simply insert the
<p>
element in all the places it may be viewed and set the CSS to only show the default in the initial state and hide the other. Then using an@media
rule you can show the alternate one when the screen size meets your requirement. Try this:Working example
If you try resizing the output frame of the jsFiddle you can see the effect working.
Give an ID to the element and remove every occurence of it before inserting a new one 🙂
If you need multiple of these elements, you could do it on the same way, but with classes instead of id’s.
I think @Roy McCrossan’s media queries way is the best solution. But since you’re asking for a JS solution (useful if maybe you need to do something else acording to screen size), this is the problem.
}
Basically, you should either move the
p
or check if already exists before inserting a new one.Better insert the
p
s in your HTML and display them acording to screen size.Other (better) option is to add a class name to the
body
or any other parent element and display/hide the elements with CSS.Other option is to keep track of the resizes and only perform the changes when neccesary, instead of every time
resize
is fired.This Solution should work for you 🙂
Fiddle: https://jsfiddle.net/3k46bhhs/1/