Increment a font size onclick event - javascript

In the new JS, I would like to understand how to make a simple increase of a font size of a text.
My goal is to onclick the text and sees increasing.
I tried something like that without success:
function increaseFontSize(objId) {
obj = document.getElementById(objId);
//get current font size of obj
currentSize = parseFloat(obj.style.fontSize); //parseFloat gives you just the numerical value, i.e. strips the 'em' bit away
obj.style.fontSize = (currentSize + .1) + "em";
}
I would like to see a demo with the new JS like the querySelector or else to solve this simple issue to allow me to learn the correct way.

The style property of an element only returns style information that has been set on the style attribute in the HTML. If the style has been set via a class or through JavaScript, you will get undefined. Instead, use getComputedStyle(), which will return the current style information, regardless of how it was set.
Also, you probably don't want to increase the font size with:
currentSize + .1 + "em"
Since em is a unit that is relative to the size of the parent element. If say, an element has parent element with a font size of 16px (the default size of normal text in most browsers) and you strip off the px and then add .1em to it, you'll have a new size of 16.1em, which means 16.1 times the parent element size (16 x 16.1 = 257.6px). If you really want to use em, you should just make it 1.1 for a slight size increase, otherwise stick with px and just bump it up by 1 (shown below).
// Instead of the function only being able to work when an element
// id is passed to it, have the function work as long as an element
// reference itself is passed to it. This is more flexible, since
// not all elements will have an id.
function increaseFontSize(element) {
console.clear();
currentSize = parseFloat(getComputedStyle(element).fontSize);
console.log("Original size of: " + element.nodeName + ": " + currentSize);
element.style.fontSize = ++currentSize + "px"; // Bump up the font size by 1 and concatenate "px" to the result
console.log("New size of: " + element.nodeName + ": " + getComputedStyle(element).fontSize);
}
// Set a click event on the entire document
document.addEventListener("click", function(event){
// Run the callback and pass a reference to the actual element that was clicked
increaseFontSize(event.target);
});
<p>A long time ago</p>
<div>In a galaxy far far away</div>
<h1><div>STAR WARS</div></h1>

Get the font-size of your element (with getComputedStyle function), increase it, then assign it to the element again:
document.getElementById('myText').addEventListener("click", function () {
let fontSize = parseInt(window.getComputedStyle(this, null).getPropertyValue('font-size'));
fontSize++;
this.style.fontSize = fontSize + 'px';
});
<div id="myText">My text</div>

You want to do something like the following.
const p = document.querySelector('p');
p.addEventListener("click", updateFontSize);
function updateFontSize() {
const style = window.getComputedStyle(p, null).getPropertyValue('font-size');
const fontSize = parseFloat(style);
p.style.fontSize = (fontSize + 10) + 'px';
}
<p>Test</p>

Here is a code-sandbox demo. We are getting fontSize from computed styles and then incrementing.
https://codesandbox.io/s/pedantic-platform-4zndi

Related

How Can I set variable width with !importanat using JavaScript/jQuery

Ia have a div named "#idDayNrCell". I want to get its width then do some calculations and apply it to another div called ".event". I am using bootstrap so i need to apply !important aswell. I am new to javascript/jquery.
I tried something like this. But it didn't wotk
$(document).ready(function(){
var cellWDTstr = ($("#idDayNrCell").css("width")); //get width
var cellWDT = cellWDTstr.substr(0,cellWDTstr.length-2); //remove the "px" part
console.log(cellWDT);
var GunSayisi=2; //how long is the event (2 for example)
// after tihs things get complicated for me
// if the even is minimum 2 days i need a different width. calculated below
var wdtEnAz2 = ((cellWDT-30)*GunSayisi + 30*(GunSayisi-1)).toString();
console.log(wdtEnAz2);
var setWdt = GunSayisi>1 ? wdtEnAz2 : calWdt;
//after here it is expoerimental code which I am failed
console.log(setWdt);
setWdt+= 'px';
console.log(setWdt);
$(".event").style.setPsetProperty('width',setWdt,'important');
});
this is the html
Using ES6,
var width = "100px";
$(".event").attr('style', `width: ${width} !important`);
Add like this :
$('.event').attr('style', 'width: '+ setWdt +' !important');
You can use css property from jquery, please find below code snippet :
$(".event").css( "width", function(
setWtd ) {
return setWtd + '!Important';
});

How to find the height of the var that has html content in it

function appData (arg) {
var tmp ='<div class="eventPopUp" z-index:6;">asdfasd <br> asdfasd <br> asdfasd <br> asdfasd<div style="clear:"></div></div>'
$(arg).html(tmp);
var off= $(tmp).offset().left;
var wid = $(tmp).width();
//var hei = $(arg).children().height();
var hei = $(tmp).outerHeight();
console.log('width is ' + wid + ' height is ' + hei);
}
Hi in above function i am making a variable that has html elements in it and i want to know the height and width of the tmp variable(becasue the content gets updated dynamically) My problem is i can get the width of the variable tmp by using width() method and i am getting height 0 by using height() method. please help me to find the height of the var tmp. and if i explictly give height by using style then height() method is giving proper answer and arg is 'li' were i append this varible.
jQuery seems to be confused as to exactly which element you are selecting when doing $(tmp) and therefore returns an empty height.
If you define the string as an object explicitly on initialisation, the height can be calculated once it's attached to the DOM. Try this:
function appData(arg) {
var $tmp = $('<div class="eventPopUp">asdfasd <br> asdfasd <br> asdfasd <br> asdfasd<div style="clear:"></div></div>')
$(arg).append($tmp);
var off = $tmp.offset().left;
var wid = $tmp.width();
var hei = $tmp.outerHeight();
console.log('width is ' + wid + ' height is ' + hei);
}
Example fiddle
The reason why you are getting 0, is most likely because you are reading the height before the element has any content in it. In other words, try using document ready
$( document ).ready(function() {
// call appData function here
});
If this doesn't work, try using setTimeout
x = setTimeout(function() {
// call appData or read height and if height of my selection is != 0 then
// {
// clearTimeout(x);
// myHeight = height of my selection
// call function that does something with it and send it as a param
// }
}, 1000);
You check for the height every second until the height is different from 0. This is a hack, I don't recommend it, unless you start leaving forehead marks on the wall.

How to get margin value of a div in plain JavaScript?

I can get height in jQuery with
$(item).outerHeight(true);
but how do I with JS?
I can get the height of the li with
document.getElementById(item).offsetHeight
but i will always get "" when I try margin-top:
document.getElementById(item).style.marginTop
The properties on the style object are only the styles applied directly to the element (e.g., via a style attribute or in code). So .style.marginTop will only have something in it if you have something specifically assigned to that element (not assigned via a style sheet, etc.).
To get the current calculated style of the object, you use either the currentStyle property (Microsoft) or the getComputedStyle function (pretty much everyone else).
Example:
var p = document.getElementById("target");
var style = p.currentStyle || window.getComputedStyle(p);
display("Current marginTop: " + style.marginTop);
Fair warning: What you get back may not be in pixels. For instance, if I run the above on a p element in IE9, I get back "1em".
Live Copy | Source
Also, you can create your own outerHeight for HTML elements. I don't know if it works in IE, but it works in Chrome. Perhaps, you can enhance the code below using currentStyle, suggested in the answer above.
Object.defineProperty(Element.prototype, 'outerHeight', {
'get': function(){
var height = this.clientHeight;
var computedStyle = window.getComputedStyle(this);
height += parseInt(computedStyle.marginTop, 10);
height += parseInt(computedStyle.marginBottom, 10);
height += parseInt(computedStyle.borderTopWidth, 10);
height += parseInt(computedStyle.borderBottomWidth, 10);
return height;
}
});
This piece of code allow you to do something like this:
document.getElementById('foo').outerHeight
According to caniuse.com, getComputedStyle is supported by main browsers (IE, Chrome, Firefox).
I found something very useful on this site when I was searching for an answer on this question. You can check it out at http://www.codingforums.com/javascript-programming/230503-how-get-margin-left-value.html. The part that helped me was the following:
/***
* get live runtime value of an element's css style
* http://robertnyman.com/2006/04/24/get-the-rendered-style-of-an-element
* note: "styleName" is in CSS form (i.e. 'font-size', not 'fontSize').
***/
var getStyle = function(e, styleName) {
var styleValue = "";
if (document.defaultView && document.defaultView.getComputedStyle) {
styleValue = document.defaultView.getComputedStyle(e, "").getPropertyValue(styleName);
} else if (e.currentStyle) {
styleName = styleName.replace(/\-(\w)/g, function(strMatch, p1) {
return p1.toUpperCase();
});
styleValue = e.currentStyle[styleName];
}
return styleValue;
}
////////////////////////////////////
var e = document.getElementById('yourElement');
var marLeft = getStyle(e, 'margin-left');
console.log(marLeft); // 10px
#yourElement {
margin-left: 10px;
}
<div id="yourElement"></div>
Here is my solution:
Step 1: Select the element
Step 2: Use getComputedStyle and provide the element to it
Step 3: Now access all the properties
const item = document.getElementbyId('your-element-id');
const style= getComputedStyle(item);
const itemTopmargin = style.marginTop;
console.log(itemTopmargin)
It will give you margin with px units like "16px" which you might not want.
You can extract the value using parseInt()
const marginTopNumber = parseInt(itemTopmargin)
console.log(marginTopNumber)
It will give you the numerical value only (without any units).

JavaScript drag and drop issue

Ok I have created a JavaScript page where the user can add text, they can set the colour, bold italics, as well as size and font. Size and drop options are selected through drop down boxes.
It looks a bit messy atm, as I am not worried about the looks, just the functionality.
When they add an element which appears in the widget, they can drag the element into position onto an image I have created which is displayed on the screen. Whenever the user is happy with the position of the text, they click save which generates the coordinates and updates the table X and Y coordinates field, At this point, a new row is generated and they can repeat the process of adding a new element. Whenever they are happy, they click save and it will send to a database to store it to be retrieved later.
My problem is everytime I add a new text field, it pushes the element down by a certain amount.
I rectified this by adding a decrementing variable which takes the elementCount (which autoincrements every time they add a new label element) and multiply it by a set amount to decrement by
decr -= (elementCount* 16);
This works fine for the medium text size, however when you start adding different text sizes and font combinations, it will change how much the element gets pushed down so it gets worse and worse every other element you add.
The new element is added like this
elementCount++;
var Text = textArray[textArray.length-1];
var Font = fontArray[fontArray.length-1];
var Color = colorArray[colorArray.length-1];
var Bold = boldArray[boldArray.length-1];
var Size = sizeArray[sizeArray.length-1];
var Italics = italicsArray[italicsArray.length-1];
var X = xCordArray[xCordArray.length-1];
var Y = yCordArray[yCordArray.length-1];
var newdiv = document.createElement('div');
newdiv.innerHTML = "<span><font color='" + Color + "' size = '" + Size + "' face='" + Font + "'><label class = 'drag2' id = 'text" + firstCount + "'> " + Text + "</label></font></span>";
document.getElementById(divName).appendChild(newdiv);
var decr= 32;
decr-= (elementCount* 16);
Y = parseInt(Y) + test;
X = parseInt(X) + 24;
document.getElementById("text" + elementCount).style.left = X + "px";
document.getElementById("text" + elementCount).style.top = Y + "px";
The drag and drop JavaScript code was based on this tutorial
http://luke.breuer.com/tutorial/javascript-drag-and-drop-tutorial.aspx
Is there any way to make it so when you dynamically add a new element , it doesn't automatically push it down the screen by a bit each new element you add. I have tried soo many different options to fix this over the past few days and have had no luck.
Thanks in advance for any help
Edit CSS for the text element
.text1{
position: relative;
left: 0px;
top: 0px;
}
I changed to absolute positioning and placed it inside a relative positioned container and works perfectly now!!

How to find the width of a div using vanilla JavaScript?

How do you find the current width of a <div> in a cross-browser compatible way without using a library like jQuery?
document.getElementById("mydiv").offsetWidth
element.offsetWidth (MDC)
You can use clientWidth or offsetWidth Mozilla developer network reference
It would be like:
document.getElementById("yourDiv").clientWidth; // returns number, like 728
or with borders width :
document.getElementById("yourDiv").offsetWidth; // 728 + borders width
All Answers are right, but i still want to give some other alternatives that may work.
If you are looking for the assigned width (ignoring padding, margin and so on) you could use.
getComputedStyle(element).width; //returns value in px like "727.7px"
getComputedStyle allows you to access all styles of that elements. For example: padding, paddingLeft, margin, border-top-left-radius and so on.
Another option is to use the getBoundingClientRect function. Please note that getBoundingClientRect will return an empty rect if the element's display is 'none'.
var elem = document.getElementById("myDiv");
if(elem) {
var rect = elem.getBoundingClientRect();
console.log(rect.width);
}
You can also search the DOM using ClassName. For example:
document.getElementsByClassName("myDiv")
This will return an array. If there is one particular property you are interested in. For example:
var divWidth = document.getElementsByClassName("myDiv")[0].clientWidth;
divWidth will now be equal to the the width of the first element in your div array.
Actually, you don't have to use document.getElementById("mydiv") .
You can simply use the id of the div, like:
var w = mydiv.clientWidth;
or
var w = mydiv.offsetWidth;
etc.
call below method on div or body tag onclick="show(event);"
function show(event) {
var x = event.clientX;
var y = event.clientY;
var ele = document.getElementById("tt");
var width = ele.offsetWidth;
var height = ele.offsetHeight;
var half=(width/2);
if(x>half)
{
// alert('right click');
gallery.next();
}
else
{
// alert('left click');
gallery.prev();
}
}
The correct way of getting computed style is waiting till page is rendered. It can be done in the following manner. Pay attention to timeout on getting auto values.
function getStyleInfo() {
setTimeout(function() {
const style = window.getComputedStyle(document.getElementById('__root__'));
if (style.height == 'auto') {
getStyleInfo();
}
// IF we got here we can do actual business logic staff
console.log(style.height, style.width);
}, 100);
};
window.onload=function() { getStyleInfo(); };
If you use just
window.onload=function() {
var computedStyle = window.getComputedStyle(document.getElementById('__root__'));
}
you can get auto values for width and height because browsers does not render till full load is performed.

Categories