Javascript: Check screen width and remove HTML element - javascript

I have a page that has 2 sliders; 1 for mobile devices & tablets (smaller than 500px screen width) and one for desktops (larger than 500px screen width). I am using CSS (display: block, display:none) attributes to display them accordingly, however, the browser is downloading the images of both sliders. I need a Javascript code that can;
Identify the screen width
Remove the desktop slider div by CSS class if the screen width is smaller or equal to 500px,
Remove the mobile slider div by CSS class if the screen width is larger than 500px.
I cannot use JQuery because of some issues we have with the library and the way the website is designed (long story).
Here are the HTML elements;
<div class="show-desktop">
[rev_slider alias="slider"][/rev_slider]
</div>
<div class="show-mobile">
[rev_slider alias="slider-mobile"][/rev_slider]
</div>

Check out this snippet:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test</title>
<style type="text/css">
.show-mobile{
display: none;
}
#media only screen and (max-width: 500px) {
.show-desktop {
display: none;
}
.show-mobile{
display: block;
}
}
</style>
<script type="text/javascript">
const vw = Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0);
const vh = Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0);
</script>
</head>
<body>
<script type="text/javascript">
if(vw > 500){
document.writeln('<div class="show-desktop">');
document.writeln('\t[rev_slider alias="slider"][/rev_slider]');
} else {
document.writeln('<div class="show-mobile">');
document.writeln('\t[rev_slider alias="slider-mobile"][/rev_slider]');
}
</script>
</div>
</body>
</html>
CSS:-
Firstly we hided class .show-mobile using display: none;.
Next we created new CSS rule, exclusively for screens whose maximum width is 500px or less using #media only screen and (max-width: 500px).
Finally, inside the rule, we hided class .show-desktop and displayed class .show-mobile.
JavaScript:-
Inside head section, we save view-port height and width in constants vw and vh, respectively.
Inside body section, we add <div> with appropriate class to the document according to the view-port's width.

Related

totally remove particular div in mobile view

this is my html
<div id="lan">
NlEn
</div>
this is my css try
#media all and (max-width: 980px) {
#lan{
display:none;
}
}
if i try this above css then div is not visible in mobile view, that is ok but when i see in inspect element that particular div is available there, i dont want to show this in inspect element also. i want to delete it totally.
this is my javascript try
var mq = window.matchMedia('all and (max-width: 700px)');
if(mq.matches) {
$(function(){
$('#lan').remove();
});
}
The above code show me an error like this
JQMIGRATE: Migrate is installed, version 1.4.1
(index):420Uncaught TypeError: $ is not a function
at (index):420
(anonymous) # (index):420
What should i do?
Use the following code.
$(document).ready(function(){
var width = screen.width,
height = screen.height;
if (screen.width <= 320 || screen.height <= 176) {
$('#lan').remove();
}
});
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<div id="lan">
NlEn
</div>
</body>
</html>
If you cannot remove the div, I suggest getting its parent element.

Setting element width to an element width a percentage width not correct on page load

I'm trying to set an element's width equal to another element's width.
The problem is that when the 2nd element has a percentage width, jQuery's .width() function returns the incorrect width when the page is first loaded.
If I do the same after the page is loaded, such as in an onclick function, then .width() returns the correct size of the element.
It is just when the page is first loaded, as if css hasn't finished calculating the actual elements width from the percentage.
Here is some code :
CSS :
#first {
width:50%;
}
Javascript :
$(function(){
function resizeResults() {
$("#results").css("width", $("#first").width());
}
resizeResults();
});
So, that will not return the correct size of the #results element. If I call this function via an onclick method, then it sets it to the proper width. JavaScript/jQuery should account for css percentages being loaded before executing code, right?
You must change this:
function resizeResults() {
$("#results").css("width", $("#first").width());
}
to this:
function resizeResults() {
$("#results").css("width", $("#first").width() + 'px');
}
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js"></script>
<style>
div {
height: 100px;
background-color: #acacac;
margin: 10px;
}
</style>
<script>
$(function ()
{
function resizeResults()
{
$("#results").css("width", $("#first").width() + 'px');
}
resizeResults();
});
</script>
</head>
<body>
<div id="first" style="width:200px;">Div first</div>
<div id="results" style="width:400px">Div result</div>
</body>
</html>

Change logo image based on screen resolution of the browser

I have two images, one with the logo in black and one with the logo in white. I would like to have the white logo when the browser is less than 768px width and black logo when it's bigger. I tried something but is not changing in real time, only if I reload the page.
$(function() {
if($(window).width() < 768){
$('.logo').find("img").attr("src","/images/Trin-02.png");
}
else{
$('.logo').find("img").attr("src","/images/Trin-01.png");
}
});
Any suggestion? Thank you
https://api.jquery.com/resize/
You are correctly checking for the window's width, but you are only doing it when the page first loads in!
Instead, use the resize function to run a script every time the screen is resized
$(window).on("resize", function(){
if($(window).width() < 768){
$('.logo').find("img").attr("src","/images/Trin-02.png");
}
else{
$('.logo').find("img").attr("src","/images/Trin-01.png");
}
})
though this sounds more like a job for css media queries, though we don't about all your needs and requirements :)
You can do it just with css and media queries.
img {
width: 400px;
content:url("http://mnprogressiveproject.com/wp-content/uploads/2014/02/kitten.jpg");
}
#media screen and (max-width: 768px) {
img {
content:url("http://images6.fanpop.com/image/photos/34800000/Kittens-3-animals-34865509-1680-1050.jpg");
}
}
<img alt="">
I have a pure JavaScript solution
document.getElementsByTagName("BODY")[0].onresize = function() {
if (window.outerWidth < 768) {
document.getElementById("img").src = yourFirstImage.png;
} else {
document.getElementById("img").src = yourSecondImage.png;
}
}
If you have the vector version of logo, make an imgname.SVG then change color using css. (SVG is scalable vector graphics and lmage will be of good quality)
HTML
<div class="logo"> <img src="images/imagename.svg"> </div>
CSS
#media only screen and (max-width: 768px) {
.logo img{
background-color:#000;
height:50px;
width:100%;
}
}
Here is the most simple solution, using CSS3 media queries,
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>media queries</title>
<style>
#media screen and (max-width: 780px) {
body {
background-image: url("/images/Trin-02.png");
}
}
#media screen and (min-width: 780px) {
body {
background-image: url("/images/Trin-01.png");
}
}
</style>
</head>
<body>
</body>
</html>
So, u can have image acc. to device you are using
There is no need to target the image multiple times. Save a reference once, use it multiple times.
Create a callback function for the resize event and bind it. That way you can also call the callback function to set the right image on init.
var image = $('.logo').find("img");
function setImage() {
var windowWidth = window.innerWidth,
src = (windowWidth < 768) ? '/images/Trin-02.png' : '/images/Trin-01.png';
image.attr('src', src);
}
$(window).on('resize', setImage);
setImage();
https://jsfiddle.net/0nxdpdp6/1/

How to start page at center of center or at specific height after load

I want to start page at the center horizontally and vertically when it had loaded (not at top), anyone any suggestions? Or at a specific height if that is possible. Thank you!
You can Do it like this:
$(document).ready(function() {
$(window).scrollTop($(window).height()/2);
$(window).scrollLeft($(window).width()/2);
});
You can change the position to what suit your needs.
Also you can use $(window).scrollTo($(window).width()/2, $(window).height()/2);
not sure what you are asking but have you tried relative coordinates ?
like >>
/*i put this all css selector for canceling all margins, paddings so i can remove default browser prefereces for the same*/
/*border box is just that any size od div is not changed after addinational padding*/
*{margin:0;padding:0;box-sizing:border-box;}
body{
position:absolute;
width:100%;height:100%;
background-color:red;
padding-top:10%;
padding-left:10%;
padding-right:10%;
padding-bottom:10%;
}
centerd{
/*relative dimensions wont work if not display:block;*/
display:block;
width:100%;height:100%;
background-color:blue;
}
<!doctype html>
<html>
<meta charset = "UTF-8" />
<title>Center Content</title>
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<body>
<centerd>
<!--html5 element, you can create your own -->
</centerd>
</body>
</html>
for more information visit : it is cool way to know enough about html, css, javascript etc.
Although not sure if this is what you are looking for:
To center a container (a DIV element say) horizontally, give it a fixed width and auto left and right margins in CSS:
div#container
{ width: 1024px; /* a fixed width container */
border: thin solid green; /* debug, to see */
margin-left: auto;
margin-right: auto;
}
then an anonymous JavaScript function to center a container vertically after load using its margin-top property:
function ()
{ var e = document.getElementById("container");
var eHeight = e.offsetHeight;
var clientHeight = document.documentElement.clientHeight;
var marginTop = 0;
if(clientHeight > eHeight)
{ marginTop = (clientHeight - eHeight) >> 1; // integer divide by 2
}
e.style.marginTop = marginTop + "px";
}
added to the page using jQuery's ready() function for the window, and HTML
<div id="container">
hello this is page content
</div>
centers a container element in the viewport where possible
Old question but I just use:
function Scrolldown() {
window.scroll(250, 400);
}
window.onload = Scrolldown;

Print image from Javascript

i have some images .... the size of each image is different
For example:
img1 = 200 x 1900
img2 = 1800 x 400
img3 = 600 x 800
// HTML
<html>
<body>
<img src='img1.jpg'>
<img src='img2.jpg'>
<img src='img3.jpg'>
</body>
</html>
// javascript
var mywindow = window.open('', 'my div');
mywindow.document.write('<html><head><title>my div</title>');
mywindow.document.write('</head><body >');
data = "<img src='img1.jpg'><img src='img2.jpg'><img src='img3.jpg'>";
mywindow.document.write(data); // data = all image
mywindow.document.write('</body></html>');
mywindow.print();
mywindow.close();
Now the output is all images printed but the sizes is corrupted
how can i print each image in page A4 and print it fitted in page (A4)
You can define CSS rules for printing and base the dimensions on 21cm x 29.7cm.
For example :
<style type="text/css">
#media print {
img {
max-width: 18cm;
max-height: 8cm;
}
}
</style>
Note that if your page is simple enough, you don't have to build a new layout in a new window as you can simply define different rules for #media print and #media screen.
You can't. Websites are created for screens, not printers.
However you could force the web browser to display the page with the same pixel dimensions as A4. However, there may be a few quirks when things are rendered.
<!DOCTYPE html>
<html>
<head>
<style>
body {
height: 842px;
width: 595px;
/* to centre page on screen*/
margin-left: auto;
margin-right: auto;
}
</style>
<head>
<body>
</body>
</html>
The best solution for printing, is to use PDFs, that's what they are for. Create a PDF that has the same data. You have full control over the print format in that case.

Categories

Resources