Resizing font based on screen width - javascript

Can someone help me with JavaScript code that resizes a font in a div if the screen width is lower than 1100px
if (window.screen.width <= 1100) {
var item = document.getElementById("div1");
item.style.fontSize = "25px";
item.innerHTML = "String";
}
This is what I have so far. Can someone help me with what to do next?

Your code works for me in JS Fiddle. Perhaps you are not specifying the correct id for your div or something like that.
http://jsfiddle.net/trott/GqFPY/
If you are hoping the code will be triggered on a browser resize, you will need to bind it to an event. (See Michael's answer.)

You will need to bind the action to the window.onresize event:
var resizeFonts = function() {
var item = document.getElementById("div1");
if (window.screen.width <= 1100) {
item.style.fontSize = "25px";
item.innerHTML = "String";
}
// Otherwise set a larger font
else item.style.fontSize = "30px";
};
window.onload = resizeFonts;
window.onresize = resizeFonts;

I have an OLD blog in which I posted about changing the font size, but it was made to show how to use jQueryUI slider. Maybe you can use some of the logic there to create your own solution:
http://weblogs.asp.net/thiagosantos/archive/2009/03/21/my-first-time-with-jquery-ui.aspx

Related

Add/Remove class from specific div based off screen size

I need to add the class .full-page when the screen size is >= 769px and remove the same class when screen size is <=768. The div I need the class to be applied to has an ID of #here I have tried quite a few things and this is where I left off...
<script>
var windowSize = window.innerWidth;
if (windowSize >= 769) {
console.log('Greater than 768');
document.getElementById('here').addClass = 'full-page';}
else (windowSize <= 768) {
console.log('Less than 768');
document.getElementById('here').removeClass = 'full-page';}
</script>
Anyone have a tip? Thanks in advance!
You can use window#matchMedia to detect width changes, and see if it matches a certain criteria. Use classList to add and remove classes.
You can see an example here. Change the width of the bottom right rectangle by dragging the border.
Code:
var classList = document.getElementById('here').classList;
var minWidth769 = window.matchMedia("(min-width: 769px)");
function match() {
minWidth769.matches ? classList.add('full-page') : classList.remove('full-page');
}
minWidth769.addListener(match);
match();
There is no method add|remove Class in JavaScript, if you want to change class for an element, you can use
document.getElementById('here').className = 'full-page'
OR
document.getElementById('here').setAttribute('class', 'full-page')
I think you need to use jQuery if you want to use 'addClass', after link the jQuery file,
Try
$("#here").addClass("full-page");
and
$("#here").removeClass ("full-page");

Dynamically adding a close button (Javascript)

Trying to add a 'X' - close button for a google maps marker. The markers will show small on the map but will enlarge when clicked (same marker, just increasing the size). I can add a close button but cannot get it to work (reduce the size back to original). Solutions need to be dynamically added please.
Fiddle: https://jsfiddle.net/gost1zLd/
var div = document.createElement('div');
div.style.width = '100px';
div.style.height = '100px';
div.style.background = 'black';
var img = document.createElement('img');
img.style.width = '100%';
img.style.height = '100%';
img.src = '';
var exit = document.createElement('div');
function large()
{
div.classList.add("large");
if (div.className == "large")
{
div.style.width = '300px';
div.style.height = '300px';
exit.innerText = 'X';
exit.style.width = '20px';
exit.style.height = '20px';
exit.style.fontSize = 'xx-large';
exit.style.fontWeight = 'bold';
exit.style.color = 'white';
exit.style.position = 'absolute';
exit.style.top = '5px';
exit.style.left = '265px';
}
}
function close()
{
div.classList.remove("large");
}
document.body.appendChild(div);
div.appendChild(img);
div.appendChild(exit);
div.addEventListener('click', large, false);
exit.addEventListener('click', close, false);
}
The problem is that removing the class large is not enough to reset the <div> to its original state since class large in itself is meaningless because it has no CSS definition. My advice is to move the styling to CSS instead of JavaScript. See fiddle: https://jsfiddle.net/gost1zLd/1/.
If you make separate functions, you can use start() again in your close() function to reset the original style. I've refactored your code a bit, hope it's self explanatory:
function close () {
div.classList.remove("large");
start();
}
Only problem with your setup is you will rebind everything when you would call start() on close(). Instead, try to separate functionality and the issue becomes clear.
DEMO
Additionally you can optimize the dynamic styling with some helper functions.
You need a function to convert a literal object to a css string.
You need a function to extend objects, similar to jQuery's $.extend() in order to set the style at once (doc) for both states (normal and large).
this.divStyle = convertLiteralToQs(cfg.div.style);
this.divLarge = convertLiteralToQs(extend(cfg.div.style, cfg.div.large));
this.div.style.cssText = this.divStyle; // normal style
this.div.style.cssText = this.divLarge; // large style
This will speed up the browser reflow for dynamic styling in JavaScript.
DEMO
Using this approach you can now more easily "style your logic" cross referencing the HTML DOM style object.

jQuery window width not equal to CSS's window width

I'm using the following two pieces of CSS and JS code:
#media (max-width: 720px) {
// a code to make arrows in a carousel disappear
}
if(jQuery(window).width() <= 720){
// a code to make arrows in the carousel stop working
}
The problem with them is that the latter executes on exactly width=738px and not 720px. I suspect that this is because of browser's vertical scrollbar that has width equal to 18px in Chrome.
Is there a way to unify this? I'd like these actions to happen at the same moment in all browsers regardless of the scrollbar's width.
Tests (when browser is # 720px and CSS has already executed):
jQuery(document).innerWidth() = 703
jQuery(window).innerWidth() = 703
jQuery(document).width() = 703
jQuery(window).width() = 703
jQuery('body').width() = 703
jQuery('html').width() = 703
I had to tackle the same problem a while ago, and so far the most correct solution I found is to use media queries to pass the actual window size to Javascript. You have to follow these steps:
Add a hidden element to your page,
Use media queries to alter the max-width property of that element,
Read back the max-width property of that element through Javascript.
For instance, add the following element to your page:
<div id="currentMedia"></div>
Then write the following CSS rules:
#currentMedia {
display: none;
}
#media (max-width: 720px) {
/* Make arrows in the carousel disappear... */
#currentMedia {
max-width: 720px;
}
}
Then, from the Javascript side, you can write:
if (parseInt(jQuery("#currentMedia").css("max-width"), 10) <= 720) {
// Make arrows in the carousel stop working...
}
And it will be accurate regardless of the scrollbar size, since the value comes from the same media query that triggers the carousel's disappearance.
I tested this solution on all major recent browsers, and it gives correct results.
You will find the big summary of what properties are supported on what browsers on this page on quirksmode.org.
Your best bet is probably to grab an element in the page (using document.body where supported, or document.getElementById or whatever), walk its offsetParent chain to find the topmost element, then examine that element's clientWidth and clientHeight.
innerWidth documentation
innerWidth() says this method is not applicable to window and document objects; for these, use .width()
try
How can I get the browser's scrollbar sizes?
From Alexandre Gomes Blog
function getScrollBarWidth () {
var inner = document.createElement('p');
inner.style.width = "100%";
inner.style.height = "200px";
var outer = document.createElement('div');
outer.style.position = "absolute";
outer.style.top = "0px";
outer.style.left = "0px";
outer.style.visibility = "hidden";
outer.style.width = "200px";
outer.style.height = "150px";
outer.style.overflow = "hidden";
outer.appendChild (inner);
document.body.appendChild (outer);
var w1 = inner.offsetWidth;
outer.style.overflow = 'scroll';
var w2 = inner.offsetWidth;
if (w1 == w2) w2 = outer.clientWidth;
document.body.removeChild (outer);
return (w1 - w2);
};
in your code
if(jQuery(window).width()-getScrollBarWidth(); <= 720){
// a code to make arrows in the carousel stop working
}
A bit outdated thread, but i've found this solution
function getWidth(){
return ((window.innerWidth > 0) ? window.innerWidth : screen.width);
}
If you are using Bootstrap > 3 then I will suggest you something.
Bootstrap ships with .container class in its Css and predefined. And its altering with #media queries.So my working code sample for this is below.
function detectWidth(){
var width = $('.container').eq(0).outerWidth() ;
console.log(width);
if(width<750){
// do something for XS element
}else if(width>=750 && width<970){
// do something for SM element
}else if(width>=970 && width<1170){
// do something for MD element
}else{
// do something for LG element
}
}
I realize this is an old thread, but I think it can still benefit from this answer.
var width = window.outerWidth;
This will give you the width of the window including scrollbars, which is what media queries use, I believe.

Why is my image not loading?

At http://blajeny.com I have:
jQuery('body').click(function(event_object)
{
spark(event_object.pageX, event_object.pageY);
});
function spark(x, y)
{
console.log('Spark called.');
var image_object = new Image();
image_object.onLoad = function()
{
image_object.style.position = 'absolute';
image_object.style.zIndex = 1;
image_object.style.top = y;
image_object.style.left = x;
}
image_object.src = '/img/spark.png';
}
The intended effect, at this stage, is to load an image at the X and Y where the user clicked. (I want to do other things as well, like animate it, but right now I'm trying to get the image to show up where the user clicked.)
The javaScript console shows that the handler is being called, however I am not seeing what I expect, a hazy blue circle immediately below and to the right of the point where the mouse was clicked.
What can/should I do differently so it loads a fresh image below and to the right of the clicked coordinates?
Thanks,
As far as I know, the onLoad should be onload
var image_object = document.createElement('img');
image_object.onload = function() { // Note the small onload
// your code
}
// Also, append the image_object to DOM
document.body.appendChild(image_object);
I don't see you appending the image to DOM that's probably why you're not seeing it
$('body').append($(image_object));
I agree, first create an element with the "img" tag, assign the src value to it, and append it to the current div (in this case its the body), like so
var imgTag = document.createElement("img");
imgTag.src = '/img/spark.png';
document.body.appendChild(imgTag);
Hope this helps.
You never append the image to the DOM, that's why you can't see it.
You can do
document.body.appendChild(image_object);
You must also replace onLoad by onload and specify the top and left position with an unit :
image_object.onload = function() {
image_object.style.position = 'absolute';
image_object.style.zIndex = 1;
image_object.style.top = '100px';
image_object.style.left = '100px';
}
Demonstration

plain javascript code to highlight an html element

to debug some javascript code, I am looking for javascript code (preferably just js, without libraries and dependencies) that can highlight a div or span (probably by putting over it a div or span of the same size and shape with a bright color and some transparency).
I pretty sure it can be done, but I don't know how to start.
CLARIFICATION
I need to put a semi transparent div on top of my element. Modifying the background or adding borders will not help as my elements have themselves backgrounds and borders.
element.style.backgroundColor = "#FDFF47";
#FDFF47 is a nice shade of yellow that seems perfect for highlighting.
Edit for clarification: You're over-complicating things. If you ever want to restore the previous background color, just store element.style.backgroundColor and access it later.
If you're debugging in a browser that supports the CSS outline, one simple solution is this:
myElement.style.outline = '#f00 solid 2px';
If for some reason you need to use javascript here is function that temporary highlits element background
function highlight(element) {
let defaultBG = element.style.backgroundColor;
let defaultTransition = element.style.transition;
element.style.transition = "background 1s";
element.style.backgroundColor = "#FDFF47";
setTimeout(function()
{
element.style.backgroundColor = defaultBG;
setTimeout(function() {
element.style.transition = defaultTransition;
}, 1000);
}, 1000);
}
Old post, but worth adding since it shows up in searches on the topic. A simple way to achieve a highlighting effect is:
myElement.style.filter = "brightness(125%)";
function highlight(element) {
var div = highlight.div; // only highlight one element per page
if(element === null) { // remove highlight via `highlight(null)`
if(div.parentNode) div.parentNode.removeChild(div);
return;
}
var width = element.offsetWidth,
height = element.offsetHeight;
div.style.width = width + 'px';
div.style.height = height + 'px';
element.offsetParent.appendChild(div);
div.style.left = element.offsetLeft + (width - div.offsetWidth) / 2 + 'px';
div.style.top = element.offsetTop + (height - div.offsetHeight) / 2 + 'px';
}
highlight.div = document.createElement('div');
// set highlight styles
with(highlight.div.style) {
position = 'absolute';
border = '5px solid red';
}
Do you use Firebug? It makes it very simple to identify dom elements and will highlight them in the page as you walk through the dom.
Here is a function that combines the top 2 answers:
function highlight(element){
let defaultBG = element.style.backgroundColor;
let defaultOutline = element.style.outline;
element.style.backgroundColor = "#FDFF47";
element.style.outline = '#f00 solid 4px';
setTimeout(function()
{
element.style.backgroundColor = defaultBG;
element.style.outline = defaultOutline;
}, 2000);
}

Categories