Remove elements on based on window size - javascript

I want to remove a div element on mobile devices only (based on window size).
The element is an advertisement and by using CSS (display:none) is still registered on mobile devices even though the ad does not show (is just hidden), and this is making a fake impression.
My ads are inserted trough Wordpress theme options (where the ad code itself is added). And from the function I get the code in the page.
<div class="topad">
<div class="adh" id="adbox"><?php echo get_option('amn_topad'); ?></div>
</div>
I probably have the right code for this but it may be placed in the wrong place.
I have used in the header.php (where the div is located):
if ($(window).width() < 700) {
$('.topad').remove();
}
and
$(document).ready(function () {
if ($(window).width() < 700) {
$('.topad').remove();
}
});
I have also tried to make a custom.js with the same codes as before and add to functions.php
function my_scripts_method() {
wp_register_script('custom_script',
get_template_directory_uri() . '/js/custom.js',
array('jquery'),
'1.0' );
wp_enqueue_script('custom_script');
}
add_action('wp_enqueue_scripts', 'my_scripts_method');
I don't know if it's possible but a simpler and efficient way would be to prevent the div to appear by inserting an "if" directly in element
<div class="adh" id="adbox"><?php if() {echo get_option('amn_topad');} ?></div>

Removing the element completely is not the way that the industry is going - you might want to do that still, but please consider the counter-arguments:
The element won't be showing back if the screen gets resized up over the threshold
To remove the element after the user resizes down under the threshold, you must detect this behavior with JS, which complexifies the code
The element might be useful to other parts of your code
The way that is widely adopted in the industry to change display based on size width is to use media queries. Here's a quick demo to show/hide elements based on the screen size (over or under 700px) - resize your window to make it work!
#media (max-width: 700px) {
/* mobile CSS: hide .desktop div */
.desktop {
display: none
}
}
#media (min-width: 700px) {
/* desktop CSS: hide .mobile div */
.mobile {
display: none
}
}
<div class="mobile">
I appear only on mobile devices! (screen width less than 700)
</div>
<div class="desktop">
I appear only on desktop devices! (screen width over 700)
</div>

Related

Hiding Div in Small Screens without Running Server Side Code

I have a page where it will query the list of all users, and displays it in a design based on Cards component. In case screen size is small, I want to list users with all attributes using a different design. I can have two <div>s; one for large screens and other for small screen and hide <div> using media query (CSS). The question is, will there be any performance disadvantage for this case? I mean, will server side codes inside the div for large screen gets executed when screen is small, even though it is not displayed?
For example, you are browsing this page in large screen.
<div class ="show-for-small-only">
//some for loop in php and other code (A)
</div>
<div class ="show-for-small-only">
//some for loop and other php code (B)
</div>
Will code section (A) be executed but not displayed? or it will never hit that section? Note that css class "show-for-small/large-only is a media css query to display:none based on screen size.
Use CSS media queries, it's way faster that JQuery.
#media screen and (min-width: 480px) {
.show-for-small-only {
display: none;
}
}
but you should adapt the design of your card depending on viewport size and/or screen orientation instead of loading it twice with 2 different styles like :
.title-section {
position:absolute;
top:2%;
left:0%;
}
#media screen and (min-width: 480px) {
.title-section {
left: auto;
right: 0%;
}
}
The answers that you have been given are both good, yet i'll recommend you to take a look at bootstrap (http://getbootstrap.com/), with it you can do what you want just by adding a css classes to your divs.
You can try using this http://mobiledetect.net/
<?php
// Include and instantiate the class.
require_once 'Mobile_Detect.php';
$detect = new Mobile_Detect; ?>
// Execute only if the device is mobile
<?php if ( $detect->isMobile() ) { ?>
<div class ="show-for-small-only">
//some for loop in php and other code (A)
</div>
<?php } ?>
<div class ="show-for-small-only">
//some for loop and other php code (B)
</div>
Or maybe append stuff from the larger display div to the smaller display div if the screen size is small using jquery and style accordingly.
Html
<div class ="show-for-small-only" id="mobile">
// append here if mobile
</div>
<div class ="show-for-small-only">
<div id="wrapper">
//some for loop and other php code (B)
</div>
</div>
Jquery
if($(document).width() <= 450){
$("#wrapper").appendTo("#mobile");
}

JavaScript code not responding to CSS change by media query

I have a javascript function that is called when the user resizes the window and that does different things depending on whether a CSS media query (max-width) is true. In order to do that, I have a div that is made visible when the media query is triggered. The javascript code then checks the div's visibility (inside the resize event). This works great in Chrome and Firefox, but is giving me minor issues in Safari (7.0.5). If the window is resized and is around the width at which the condition is triggered, the js code is sometimes out of sync with the CSS: when I inspect the div I can see that it's showing (meaning the media query is working correctly), but the js conditional that checks visibility still returns false. The code is pretty simple:
JQuery:
if ($("#is-mobile").css("display") === "none") {
$("#site-nav").show();
} else {
$("#site-nav").hide();
}
CSS:
#is-mobile {
width: 0;
height: 0;
display: none;
}
#media screen and (max-width: 500px) {
#is-mobile {
display: block;
}
}
This mismatch only happens if the CSS width of the window is roughly between 485px and 499px. That makes me thing it's related to the ~15-20px mismatch between $(window).width() and the CSS viewport width that can occur when a vertical scrollbar is visible (see e.g. here). I do have a vertical scrollbar in my window so I wonder if that's what is causing the issues. Ironically, that scrollbar weirdness is why I'm checking the visibility of the div instead of using $(window).width() in the first place!
EDIT: just tested this code in an otherwise empty html (so no vertical scrollbar), and the problem is indeed gone. So must be related to the scrollbar.

Avoiding document.write

I am trying to apply a class name based on the width of the viewport such that it doesn't "flash" before the JavaScript gets loaded and processed.
For example, I have a Bootstrap sidebar that I want to hide by default if the user is on a mobile device. If I just add some logic to document.ready event, then the menu is visible for a split second before disappearing, which is annoying.
To circumvent that behavior, I used document.write to create the open tag for my sidebar:
<script type="text/javascript">
// Prevent flicker of menu before collapsing on small screens
if (window.outerWidth < 768) {
document.write('<aside class="collapse" id="primary-sidebar">');
} else {
document.write('<aside class="collapse in width" id="primary-sidebar">');
}
</script>
...
</aside>
While this resolves the problem, I do get warnings in Firefox about unbalanced trees and I've read that document.write should not really be used in this manner.
Is there another way to add the in width class based on the window size without waiting until after the page is all loaded?
Instead of putting the Javascript in document.ready, put the <script> tag immediately after the element in question.
<aside class="collapse" id="primary-sidebar">
...
</aside>
<script type="text/javascript">
if (window.outerwidth >= 768) {
document.getElementById("primary-sidebar").className = "collapse in width";
}
</script>
While this will briefly display the wrong size, it should resize so quickly that the flicker should be unnoticeable. I put this logic in the desktop version, since the processing should be faster.
You can use:
var aside = document.querySelector("#primary-sidebar");
if (window.outerWidth < 768) {
aside.className = "collapse";
} else {
aside.className = "collapse in width";
}
You're going to cause yourself a lot of stress by using JavaScript to handle things like hiding/showing based on screen size.
The standard way to hide/show things based on screen size is with the #media CSS rule
For example:
#media (min-width: 768px) {
#primary-sidebar {
display:none;
}
}
If you want to prevent your menu from being shown initially, set the element to
display: none;
or
visibility: hidden;
On the other hand you don't need to put it inside $(document).ready(); if your only condition is the width of the window.

How to use .load to .prepend content without page refresh?

I'm trying to use jQuery to only load certain content if the viewport is above a specified width.
This works, but not quite right. Check out the JsFiddle link at the bottom for a working demo.
Here's what I have so far;
If the viewport is below 500px #wrapper is hidden with a media query.
Above 500px #wrapper is set to visibility: visible;
jQuery is looking for element.is(':visible'). When this happens jQuery loads the image.
Resizing the browser window activates the media query, but not the jQuery.
The jQuery only fires on a page refresh.
I've tried using $( window ).resize(function() but this fires every time the viewport changes size, duplicating the content.
Is there a way to activate jQuery without a page refresh?
The ideal solution would be;
up to 500px load nothing,
when the viewport is resized above 500px load the jQuery.
If the viewport is resized below 500px unload the jQuery content.
HTML
<p>CSS hides <strong>#wrapper</strong> if viewport is below 500 pixels.</p>
<div id="wrapper">
<p>jQuery checks CSS to see if <strong>#wrapper</strong> is visible and loads image on page refresh.</p>
<p>I'm looking for a way to run this function without needing to refresh the page. I've looked into using (resize) function, but this duplicate the content.</p>
CSS
#wrapper {
visibility: none;
display: none;
}
#media only screen and (min-width: 500px){
#wrapper {
visibility: visible;
display: block;
}}
JQuery
$(function() {
var element = $(this).find('#wrapper');
if (element.is(':visible')) {
$('#wrapper').prepend('<img src="http://cache.desktopnexus.com/thumbseg/1134/1134934-bigthumbnail.jpg" alt="Demo image">');
}
JsFiddle link:
https://jsfiddle.net/tu60wbbu/13/
You can use window.matchMedia() instead of $(window).resize() to have your javascript respond to a media query match in your CSS.
https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia
It's fairly well supported across browsers.
http://caniuse.com/#search=matchmedia
If you need to support IE 9 or lower, you might have to fall back to using $(window).resize() for those browsers.
Here is the code for my comment:
$(function() {
var large = false;
var barrier = 1000;
$( window ).resize(function() {
if(!large && $(window).width() > barrier) {
large = true;
$('#wrapper').prepend('<img src="http://cache.desktopnexus.com/thumbseg/1134/1134934-bigthumbnail.jpg" alt="Demo image">');
} else if(large && $(window).width() < barrier) {
large = false;
$('#wrapper img').remove();
}
});
});
Working Fiddle: https://jsfiddle.net/tu60wbbu/14/
I used 1000px as the barrier in the demo.
You should initialize large properly by the window width on load. For demo purposes i used false as initial value.
Sorry for the long time, I was at vaccation :-)

jquery .hide() function - Hide mobile, Display Desktop

I'll try my best to set up my scenario so that you can understand my question.
My site is currently taking advantage of css media queries to span between screen resolutions. I have a main drilldown menu that can not be hidden on page load, otherwise the menu will not correctly calculate it's height, and will not display properly.
As a way to still be able to hide this menu when needed, I have found a workaround that hides the menu, yet still allows the menu to correctly calculate it's height on page load.
$(document).ready(function () {
$(".hide-menu").hide();
var $drillDown = $("#drilldown");
});
This is great for pages that do not require the main menu to be displayed initially on both mobile and desktop resolutions. However, for my product pages this solution will not work. I need the menu to hide on load for mobile resolutions, but also display on load for desktop resolutions. Can anyone think of a solution that will work? I'm stumped. Here is the HTML:
<div class="drill-down-wrapper hide-menu hide-on-load hide-pd-page">
<div id="drilldown-breadcrumbs" class="breadcrumbs skin-colorful"></div>
<div id="drilldown" class="skin-colorful">
<!-- #Include virtual="Menu.txt" -->
</div>
</div>
Use media queries to hide and show the menus based on screen resolutions.
Rather than jQuery, try using CSS to show/hide elements. You can use the display rule to do so. Just as an example:
.hide-menu-on-load {
display: none;
}
#media screen and (max-width: 680px) {
.hide-menu-on-load {
display: block;
}
}
Note: display: none removed the element from the flow of the page. visibility: hidden keeps the element's flow on the page, yet simply removes it from view

Categories

Resources