I am having issues with a js script on a menu. I have the same menu but styled differently for pc and smaller versions. And I want this script to only affect the menu when the screen is lower than x width. How can I achieve this?
This is my script
var dropdown = document.getElementsByClassName("dropdown-btn");
var i;
for (i = 0; i < dropdown.length; i++) {
dropdown[i].addEventListener("click", function() {
var dropdownContent = this.nextElementSibling;
if (dropdownContent.style.display === "block") {
dropdownContent.style.display = "none";
} else {
dropdownContent.style.display = "block";
}
});
}
}
Check the width of the window (cross-browser) then conditionally run your script.
var x = 400,
w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
if (w < x) {
console.log(w, 'true')
// do stuff here when screen is smaller
} else {
console.log(w, 'false')
// do stuff here when screen is larger
}
You can use window width property of JQuery
if ($(window).width() < x)
{
//Code here
}
To check the width of window (cross-browser), you may use window, screen and width property of JavaScript.
It might help you :
//Smaller screen sizes
var size = 768;
if(window.screen.width < size) {
//Your code for smaller screen sizes here
}
else
{
//Your code for Larger screen sizes here
}
Related
I want to change the menu text automatically when resizing the window to 768px or lower.
Any solution for that?
The code below doesn't work.
function menu() {
let w = window.outerWidth;
let y = document.getElementById("home");
if (w <= 768) {
y.innerText = "Menu";
} else {
y.innerText = "Home";
}
}
menu();
The above code works, you probably just need to call it whenever the resize event fires. Ex, if the above code is in a a function called "menu":
function menu(){
let w = window.outerWidth;
let y = document.getElementById("home");
if (w <= 768) {
y.innerText = "Menu";
} else {
y.innerText = "Home";
}
}
window.onresize = menu;
That said, though, it makes much more sense to do this with CSS media queries.
I'm trying to append a div when the mobile is in landscape mode. But I only want the div to be append once and one time only.
function doStuff() {
landscape = window.orientation ? window.orientation == 'landscape' : true;
if (landscape && window.innerWidth < 736 && window.innerWidth > 320) {
if (window.innerHeight > window.innerWidth) {
console.log("portrait");
} else {
$("body").append("<div>Test</div>");
}
}
}
window.onload = window.onresize = doStuff;
if (window.onorientationchange) {
window.onorientationchange = doStuff;
}
There's no need for JS code here - you can use CSS alone to achieve this. Media queries have the orientation restriction which you can use to display the required content:
.landscape-only { display: none; }
#media all and (orientation:landscape) {
.landscape-only { display: block; }
}
Working example
To see the content change you will just need to resize the width of the Output frame in the above Fiddle.
You can check if this div is already appended.
var appended = false;
function doStuff() {
if(appended) return;
landscape = window.orientation? window.orientation=='landscape' : true;
if(landscape && window.innerWidth < 736 && window.innerWidth > 320){
if(window.innerHeight > window.innerWidth){
console.log("portrait");
} else{
$("body").append("<div>Test</div>");
appended = true;
}
}
}
You could use one(), which fires only once
For Appending you need to use this
var $div = $('<div />').appendTo('body');
$div.attr('id', 'holdy');
Set flag = true if div is already appended.
function doStuff(){
landscape = window.orientation? window.orientation=='landscape' : true;
var flag = false;
if(landscape && window.innerWidth < 736 && window.innerWidth > 320){
if(window.innerHeight > window.innerWidth){
console.log("portrait");
}else{
if (flag == false){
$( "body" ).append( "<div>Test</div>" );
flag = true;
}else{
console.log("Div is already appended");
}
}
}
}
window.onload=window.onresize=doStuff;
if(window.onorientationchange){
window.onorientationchange=doStuff;
}
I think you can use the .one(). there is example of how use it on internet.
http://api.jquery.com/one/
I have this pop up window being centered by javascript using px. I need the box to be responsive so how can I adjust the script to calculate for percentages and not px. Is it possible? This current code allows me to produce an automatic pop up but it also has script that centers the pop using px. This is not responsive.
function toggle(div_id) {
var el = document.getElementById(div_id);
if ( el.style.display == 'none' ) { el.style.display = 'block';}
else {el.style.display = 'none';}
}
function blanket_size(popUpDivVar) {
if (typeof window.innerWidth != 'undefined') {
viewportheight = window.innerHeight;
} else {
viewportheight = document.documentElement.clientHeight;
}
if ((viewportheight > document.body.parentNode.scrollHeight) && (viewportheight > document.body.parentNode.clientHeight)) {
blanket_height = viewportheight;
} else {
if (document.body.parentNode.clientHeight > document.body.parentNode.scrollHeight) {
blanket_height = document.body.parentNode.clientHeight;
} else {
blanket_height = document.body.parentNode.scrollHeight;
}
}
var blanket = document.getElementById('blanket');
blanket.style.height = blanket_height + 'px';
var popUpDiv = document.getElementById(popUpDivVar);
popUpDiv_height=blanket_height/2-187.5;//200 is half popup's height
popUpDiv.style.top = popUpDiv_height + 'px';
}
function window_pos(popUpDivVar) {
if (typeof window.innerWidth != 'undefined') {
viewportwidth = window.innerHeight;
} else {
viewportwidth = document.documentElement.clientHeight;
}
if ((viewportwidth > document.body.parentNode.scrollWidth) && (viewportwidth > document.body.parentNode.clientWidth)) {
window_width = viewportwidth;
} else {
if (document.body.parentNode.clientWidth > document.body.parentNode.scrollWidth) {
window_width = document.body.parentNode.clientWidth;
} else {
window_width = document.body.parentNode.scrollWidth;
}
}
var popUpDiv = document.getElementById(popUpDivVar);
window_width=window_width/2-250;//200 is half popup's width
popUpDiv.style.left = window_width + 'px';
}
function popup(windowname) {
blanket_size(windowname);
window_pos(windowname);
toggle('blanket');
toggle(windowname);
}
This seems like an awful lot of javascript to display a popup dialog. You can accomplish this functionality with CSS/HTML alone, although many solutions will use HTML/CSS for the layout, and some javascript to show/hide the dialog.
I dont like to use javascript at all for the actual layout of the webpage, such as positioning elements. CSS was designed specifically for positioning and styling web elements, and it is generally more efficient than JS.
You may want to check out some of the many guides available online for HTML/CSS Modal Dialogs. These are done with minimal javascript.
Check out this one for starters
http://www.webdesignerdepot.com/2012/10/creating-a-modal-window-with-html5-and-css3/
Good luck
You really don't need JavaScript to center something - for that, we have CSS! To center something horizontally, simply use the following CSS on the element
margin: auto;
To center something vertically, you can use something like
top: 50%;
transform: translateY(-50%);
position:relative;
I am using this code to adjust the text size depending on the length of text inside the element title. This works great until the user adjusts the size of the browser. What can be done to allow the text size to be adjusted if the user's window is made smaller. Say for instance if window width is less than 600 pixels, than change font size.
How can this be made to on page load, do what the code does now - but also change font sizes when browser size is adjusted as well?
$(".title").css('font-size', function () { // get length of text for title and adjust font size
var $numWords = $(this).text().length;
if (($numWords >= 1) && ($numWords < 40)) {
return "26px";
}
else if (($numWords >= 40) && ($numWords < 60)) {
return "24px";
}
else if (($numWords >= 60) && ($numWords < 100)) {
return "22px";
}
else if (($numWords >= 100)) {
return "20px";
}
});
<div id="cont" style="font-family: Verdana; background-color: #ccc;">
<div id="textContent">fox jump over the lazy dog...fox jump over the lazy dog...fox jump over the lazy dog</div>
</div>
<script>
var textContainer = document.getElementById('cont');
var text = document.getElementById('textContent');
var textLength = text.innerText.length;
var firstLoadWidth;
if (textLength >= 1 && textLength < 40) {
cont.style.fontSize = '26px';
}
else if (textLength >= 1 && textLength < 60) {
cont.style.fontSize = '24px';
}
else if (textLength >= 1 && textLength < 100) {
cont.style.fontSize = '22px';
}
else if (textLength > 100) {
cont.style.fontSize = '20px';
}
window.addEventListener('load', function () {
firstLoadWidth = window.innerWidth;
});
window.addEventListener('resize', function () {
var getSize = window.innerWidth / firstLoadWidth;
getSize <= 1 ? text.style.fontSize = getSize + 'em' : text.style.fontSize = '1em';
}, false);
</script>
You can use jQuery's resize() function for that (http://api.jquery.com/resize/)
$(document).ready(function() {
onResize()
});
onResize = function() {
if(window.width() < 600){
// Do stuff
}
}
$(window).bind('resize', onResize);
You can measure the actual rendered size of the text like this:
var text = $(this).text();
var tmp = $("<div/>").css({position: "absolute"}).text(text);
$("BODY").append(tmp);
var width = tmp.width();
tmp.remove();
If you make sure your div is styled as it will be on the page (same font, weight, size), then this can tell you how big it will be. It should be possible to iterate this to search for a size that fits the available space (with some reasonable cutoff). This will be slow if you have hundreds or thousands of these on a page, but for a couple of titles it should be fine.
just use the percentage in your font-size
p {
font-size:200%;
}
the percentage is due to the width of the parent tags "div"
I have a resisable div with text inside. I want the text to scale as the div changes size.
Specifically, I want the text to have the largest possible font size that will make it fit inside the div.
Use FitText http://fittextjs.com/
I use this plugin that I made based on fitText.js, because fitText doesn't fit my needs, due to I don't know the length of the strings to resize, so the fix resize parameter of fitText don't work in all cases.
$.fn.adjustTextSize = function (set_max_size, min_size) {
min_size = min_size || 12; // if no value then set a default one
var string, width, line, initFontSize, returnFontSize, ratio;
return this.each(function() {
// Store the object
var $this = $(this);
var resizer = function () {
string = $this;
string.html('<span style="white-space: nowrap;">' + string.html() + '</span>');
width = string.width();
line = $(string.children('span'));
initFontSize = parseInt(string.css('font-size'));
ratio = width/line.width();
returnFontSize = initFontSize*ratio;
if (set_max_size && returnFontSize > initFontSize) {
returnFontSize = initFontSize;
}
if (min_size && returnFontSize < min_size) {
returnFontSize = min_size;
}
string.css('font-size',returnFontSize);
while (line.width() >= width) {
if (min_size && returnFontSize <= min_size) {
string.html(line.html());
return false;
}
string.css('font-size', --returnFontSize);
}
string.html(line.html());
}
// Call once to set.
resizer();
// Call on resize. Opera debounces their resize by default.
$(window).on('resize orientationchange', resizer);
});
};
$('.js-adjust-text').adjustTextSize(false, 12);
$('.js-adjust-text-limit').adjustTextSize(true, 30);
This plugin get two parameters:
set_max_size: boolean to limit maximum font size to its defined size in CSS
min_size: Integer number to limit minimum font size.
I hope it works for your case.
You can try like this:
If you want the height to adjust, try setting the height to auto
$("#sample").modal({
containerCss:{
backgroundColor:"#fff",
borderColor:"#0063dc",
height:450,
padding:0,
width:830
}
});
here is a little changed code above, because it is for getting width of container I made edit for heigh container adjustment.
$.fn.adjustTextSize = function (set_max_size, min_size) {
min_size = min_size || 12; // if no value then set a default one
var string, height, line, initFontSize, returnFontSize, ratio;
return this.each(function() {
// Store the object
var $this = $(this);
var resizer = function () {
string = $this;
string.html('<span>' + string.html() + '</span>');
height = string.height();
line = $(string.children('span'));
initFontSize = parseInt(string.css('font-size'));
ratio = height/line.height();
returnFontSize = (initFontSize*ratio) ;
if (set_max_size && returnFontSize > initFontSize) {
returnFontSize = initFontSize;
}
if (min_size && returnFontSize < min_size) {
returnFontSize = min_size;
}
string.css('font-size',returnFontSize);
while (line.height() >= height) {
if (min_size && returnFontSize <= min_size) {
string.html(line.html());
return false;
}
string.css('font-size', --returnFontSize);
}
string.html(line.html());
}
// Call once to set.
resizer();
// Call on resize. Opera debounces their resize by default.
$(window).on('resize orientationchange', resizer);
});
};
Hope it will useful