I got an sidebar which need to adjust to the document size. This works perfectly, its this code:
<script type="text/javascript">
$(document).ready(function(){
$("#sidebar").height( $(document).height() );
});
</script>
But now i got an form in my website which changes with javascript in size when you put in options. So with other words the whole document gets longer when you put in multiple options. But this script doesn't adjust to that so the sidebar just gets cut off when you put in more options.
So with other words is there an possibility to make this script adjust automatically or let the following script rerun the function when it returns:
<script>
treated = new Object();
inputNumber = 1;
function addOne() {
//Create an input type dynamically.
var divElement = document.createElement("div");
var element = document.createElement("input");
inputNumber++;
element.setAttribute("name", "input" +inputNumber);
element.setAttribute("onkeyup", "if (this.value.length > 1 && treated[this.name] != 1){ addOne(); treated[this.name] = '1'; }");
element.setAttribute("id", "productoptiesadd");
var price = document.createElement("input");
price.setAttribute("name", "price" +inputNumber);
price.setAttribute("id", "productoptiesaddprice");
var foo = document.getElementById("japroductopties");
var htag = document.createElement("h7");
htag.innerHTML = "Optie " + inputNumber + ":";
var htags = document.createElement("h7");
htags.innerHTML = " € ";
divElement.appendChild(htag);
divElement.appendChild(element);
divElement.appendChild(htags);
divElement.appendChild(price);
foo.appendChild(divElement);
}
</script>
Hope some1 can help :).
Why not setting #sidebar height property to 100% in your stylesheet ? Is Javascript really necesary ?
Otherwise, just write a function SidebarAutoAdjust() with your first code fragment :
$("#sidebar").height( $(document).height() );
Then all you have to do is calling this function at the end of your addOne() function.
Related
I would like to increase the font size of the paragraph as well as the font size of the number in the button.
I copied and pasted my sizer function from StackOverflow (a few alterations) and thought it would work and still can't get it to work. Can someone help?
Since I've spent so much time on just the first part, as a beginner programmer, I'm wondering what I am missing. Does anyone have any ideas from my code or their experience as to what I might be missing?
Thanks as always.
<html>
<button onclick='incrementer(); sizer()' id='count' value=0 />0</button>
<p id='test'>a</p>
<script>
clicks = 0
incrementer = function () {
clicks += 1
click = document.querySelector("#count").textContent = clicks;
click.innerHTML = document.getElementById("count").value = document.getElementById('test');
}
sizer = function changeFontSize() {
div = document.getElementById("test");
currentFont = div.style.fontSize.replace("pt", "");
div.style.fontSize = parseInt(currentFont) + parseInt(clicks) + "pt";
}
</script>
</html>
Some things here:
I woudn't append two functions to your onclick here. Just append one and call your second function from the first one that gets fired via onclick. That looks a lot more tidy
Don't forget to put var before every variable, without it's not valid JavaScript
I didn't quite understand what you tried with your currentFont variable, so I removed it. It's not necessary and causes the script to not working correctly
<html>
<button onclick='incrementer()' id='count' value=0 />0</button>
<p id='test'>a</p>
<script>
var clicks = 0;
var incrementer = function() {
clicks += 1;
var click = document.querySelector("#count").textContent = clicks;
click.innerHTML = document.getElementById("count").value = document.getElementById('test');
sizer();
}
var sizer = function changeFontSize() {
var div = document.getElementById("test");
div.style.fontSize = parseInt(clicks) + "pt";
}
</script>
</html>
Here's a from-scratch version that does what you're asking for. I'll point out a few things that I did to help you out.
https://codepen.io/anon/pen/VBPpZL?editors=1010
<html>
<body>
<button id="count">0</button>
<p id="test">
Lorem Ipsum is simply dummy text of the printing and typesetting industry.
</p>
</body>
</html>
JS:
window.addEventListener('load', () => {
const button = document.querySelector('#count');
const paragraph = document.querySelector('#test');
const startingFontSize = window.getComputedStyle(document.body, null)
.getPropertyValue('font-size')
.slice(0, 2) * 1;
let clicks = 0;
button.addEventListener('click', () => {
clicks++;
// this is a template literal
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
const fontSize = `${startingFontSize + clicks}px`;
button.innerHTML = clicks;
button.style.fontSize = fontSize;
paragraph.style.fontSize = fontSize;
});
});
The code runs when the page is loaded, so we attach an event listener on the window object listening for the load event.
We then store references to the button and the paragraph elements. These are const variables because their values won't change. This also limits their scope to the containing function.
We get the initial font size for the body element, because in this example we aren't explicitly setting a base font in css so we're just using the one for the document. getComputedStyle is a somewhat expensive operation, and in this case we only need to get it in the beginning because it won't change, so we also store it as a const. The value is returned as a string like "16px" but we need the number, hence the slice and multiplying by one to cast the string into a number. parseInt would also do the same thing.
Notice that clicks is defined with let. This means that the variable can be changed. var still works of course, but in modern practices its best to use const and let when declaring variables. This is partly because it forces you to think about what kind of data you're working with.
We add an event listener to the button element and listen for the click event. First, we increment the clicks variable. Then we declare fontSize using a template literal which adds our new clicks count to the startingFontSize and "px" to get a string.
Finally, the innerHTML value of the button element is updated. Then we update the fontStyle property for both elements.
The issue here is that there is no initial value for the fontSize of your <p> tag so div.style.fontSize returns an empty string.
You can use window.getComputedStyle instead of div.style.fontSize and you will get the current fontSize.
There is already a post explaining this method
https://stackoverflow.com/a/15195345/7190518
You don't have an initial font-size style on your <p> tag, so it div.style.fontSize is always empty. Also, best practice is to always use var when introducing new variables in javascript.
One good trick to help debugging things like these is to use console.log() at various points, and see whats coming out in your browser console. I used console.log(div.style.fontSize) and the answer became clear.
Working below after adding <p style='font-size:12px'>a</p>:
<html>
<button style='font-size:12px;' onclick='incrementer(); sizer()' id='count' value=0 />0</button>
<p id='test' style='font-size:12px;'>a</p>
<script>
var clicks = 0
incrementer = function () {
clicks += 1
click = document.querySelector("#count").textContent = clicks;
click.innerHTML = document.getElementById("count").value = document.getElementById('test');
}
var sizer = function changeFontSize() {
var div = document.getElementById("test");
var btn = document.getElementById("count");
var newSize = parseInt(div.style.fontSize.replace("pt", "")) + parseInt(clicks);
div.style.fontSize = newSize + "pt";
btn.style.fontSize = newSize + "pt";
}
</script>
</html>
I don't understand the logic of this solution, but you can simplify it avoiding to use a lot of var (anyway always prefer let or const if you don't need to change), using a single function and writing less code.
function increment(e){
const ctrl = document.getElementById('test');
let current = parseInt(e.dataset.size);
current += 1;
e.innerHTML = current;
e.dataset.size = current;
ctrl.style.fontSize = current + 'pt';
}
<button onclick="increment(this);" data-size="20">20</button>
<p id='test' style="font-size:20pt;">A</p>
I'am trying to identify with javascript if I need to force a page break in my document.
One element that is overflow hidden. I loop through each of the elements within this document. I remove all last childs until the height of the element within the overflow:hidden element is smaller. Now I know, when to page break and I push all removed childs in the new page.
Works fine in browser. But not in PDF...
I'am using http://wkhtmltopdf.org/
See problem here: Left: PDF, Right: Browser (Chrome)
Height of 3262px vs 358px...
Same if I use .clientHeight or jQuery .height().
Does anyone know a workaround to get heights the same?
Some code:
function isOverflowed(element){
// return element.scrollHeight > element.clientHeight;
// console.log(element.clientHeight);
// console.log(element.parent().height() +'>'+ element.height());
return element.parent().height() < element.height();
}
// var daysWrapper = document.getElementById('days');
// var days = daysWrapper.querySelectorAll(".section.day");
var days = $('#days .section.day');
// console.log(days);
days.each(function() {
var $this = $(this);
var area = $this.find('.day-info');
var content = area.children();
var lasts = $( '<div class="lasts">' );
var test = 0;
while(isOverflowed(content)) {
var last = content.children().last();
// lasts.append( $( last ) );
last.clone().prependTo(lasts);
last.remove();
test++;
if (test > 6) break;
}
content.find('h1').html(area.height() + ' - ' + content.height());
if (lasts.children().length ) {
var newPage = $this.clone();
newPage.insertAfter($this);
newPage.find('.day-image').remove();
newPage.find('.day-info').removeClass('overflow');
newPage.find('.day-info').children().html(lasts.html());
}
});
Thanks!
Scenario:
User enters text "thisisabutton" for ButtonA
User enters text "thisisalongerbutton" for ButtonB
Both buttons dynamically adapt in size to fit text length, thus making them 2 different sizes
I want ButtonA to be the same size as ButtonB (which will determine the size since it's longer than ButtonA).
What is the best approach to do this in Javascript?
<button id="ButtonA" onChange="ResizeButtons();">Hello</button>
<button id="ButtonB" onChange="ResizeButtons();">Worlddddddddddddddd</button>
<script type="text/javascript">
function getWidth(element) {
return parseInt(window.getComputedStyle ? window.getComputedStyle(element,null).getPropertyValue("width") : element.currentStyle.width );
}
function ResizeButtons() {
var buttonA = document.getElementById("ButtonA");
var buttonB = document.getElementById("ButtonB");
buttonA.style.width = "auto";
buttonB.style.width = "auto";
var buttonAWidth = getWidth(buttonA);
var buttonBWidth = getWidth(buttonB);
var maxWidth = (buttonAWidth > buttonBWidth ? buttonAWidth: buttonBWidth) + "px";
buttonA.style.width = maxWidth;
buttonB.style.width = maxWidth;
}
</script>
1) Cross Browser.
2) Resets elements to "auto" before computing, or else they'll never resize after the first character is entered.
3) Avoids re-accessing DOM after getting buttonA and buttonB.
4) Checks while each button is being modified.
EDIT
You may have to put the ResizeButtons(); event on the inputs you're using to change the button content, or better yet, simply run the function ResizeButtons() inside your current script that changes the button content, immediately after the content is changed.
<button id="ButtonA">Hello</button>
<button id="ButtonB" onChange="ResizeButtons();">Worlddddddddddddddd</button>
<script type="text/javascript">
function ResizeButtons()
{
var buttonAWidth = document.getElementById("ButtonA").style.width;
var buttonBWidth = document.getElementById("ButtonB").style.width;
var maxWidth = 0;
if (buttonAWidth >= buttonBWidth){
maxWidth = buttonAWidth;
}
else{
maxWidth = buttonBWidth;
}
document.getElementById("ButtonA").style.width = maxWidth;
document.getElementById("ButtonB").style.width = maxWidth;
}
</script>
While this answer utilizes jQuery the principles are the same as the above answers without a lot of the extra hassle of handling getting a true element width. I by no means am advocating that you should necessarily use jQuery, but I think it illustrates the solution in a more concise fashion.
The user adds a new button by providing a new name.
Calculate the longest button and reset the widths of smaller buttons
The code:
<label for="buttonName">Enter Button Name:</label><input id="buttonName">
<button id="createButton">Create Button</button>
<div id="buttons"></div>
<script type="text/javascript">
$('#createButton').button().click(function(){
var buttonName = $('#buttonName').val();
$('#buttonName').val("");
$('#buttons').append($('<button>'+buttonName+'</button>').button());
var widestButton = 0;
$('#buttons button').each(function(){
widestButton = Math.max($(this).width(), widestButton);
});
$('#buttons button').width(function(){
if ($(this).width() < widestButton)
$(this).width(widestButton);
});
});
</script>
http://jsfiddle.net/PwNUA
I don't know much about jQuery but I've been using the following javascript code to make a table keep the scroll bar location upon pageback:
<script type="text/javascript">
window.onload = function () {
var strCook = document.cookie;
if (strCook.indexOf("!~") != 0) {
var intS = strCook.indexOf("!~");
var intE = strCook.indexOf("~!");
var strPos = strCook.substring(intS + 2, intE);
document.getElementById("grdWithScroll").scrollTop = strPos;
}
}
function SetDivPosition() {
var intY = document.getElementById("grdWithScroll").scrollTop;
document.cookie = "yPos=!~" + intY + "~!";
}
</script>
and
<div id="grdWithScroll" onscroll="SetDivPosition()">
It works great for a single div. But how could I extend this for use with a second div section?
Instead of using document.getElementById, you can asign the same class name to all the divs for which you want this functionality, and then user the jQuery selector $(".scrollgrid") to select the multiple divs, and store the scroll tops. If you do not want to use jQuery, you can look at the custom functions that people have written to select the elements by class name. Here is an example.
http://www.netlobo.com/javascript_getelementsbyclassname.html
Instead of a single div id, you could use class attribute to define all the divs you want the feature to be used on.
<div id="grdWithScroll" class="coolScroll" onscroll="SetDivPosition()">
</div>
<div id="abcWithScroll" class="coolScroll" onscroll="SetDivPosition()">
</div>
Use jQuery (or other libraries) to easily select all divs with said class and access the scrollTop attribute
$('.coolScroll').each( function()
{
// do something with scrollTop
}
You could also use the class selector to set the onscroll function.
$('.coolScroll').attr( 'onscroll' , 'javascript:SetDivPosition()' );
Found what I was looking for here:
http://social.msdn.microsoft.com/Forums/nb-NO/jscript/thread/ad18ed20-8ae2-4c13-9a51-dcb0b1397349
<script language="javascript" type="text/javascript">
//This function sets the scroll position of div to cookie.
function setScrollPos() {
var div1Y = document.getElementById('div1').scrollTop;
var div2Y = document.getElementById('div2').scrollTop;
document.cookie = "div1Pos=!*" + div1Y + "*!" +
" div2Pos=|*" + div2Y + "*|";
}
///Attaching a function on window.onload event.
window.onload = function () {
var strCook = document.cookie; if (strCook.indexOf("!~") != 0) {
var intS = strCook.indexOf("!~");
var intE = strCook.indexOf("~!");
var strPos = strCook.substring(intS + 2, intE);
document.body.scrollTop = strPos;
}
/// This condition will set scroll position of <div> 1.
if (strCook.indexOf("iv1Pos=!*") != 0) {
var intdS = strCook.indexOf("iv1Pos=!*");
var intdE = strCook.indexOf("*!");
var strdPos = strCook.substring(intdS + 9, intdE);
document.getElementById('div1').scrollTop = strdPos;
}
/// This condition will set scroll position of <div> 2.
if (strCook.indexOf("iv2Pos=!*") != 0) {
var intdS = strCook.indexOf("iv2Pos=|*");
var intdE = strCook.indexOf("*|");
var strdPos2 = strCook.substring(intdS + 9, intdE);
document.getElementById('div2').scrollTop = strdPos2;
}
}
</script>
i try to make text strikethrough with javascript.
I know nothing about Javascript and try to search on the net how to that.
<script language="JavaScript">
function recal(val,sum)
{
if(sum == true)
{
var total = parseInt(document.getElementById("total").innerHTML, 10);
total+=val;
document.getElementById("total").innerHTML=total;
}
else
{
var total = parseInt(document.getElementById("total").innerHTML, 10);
total-=val;
document.getElementById("total").innerHTML=total;
var pnl = document.getElementById("totalEvents");
}
var pnl = document.getElementById("totalEvents");
var pnl2 = document.getElementById("eventCategory");
var pnl3 = document.getElementById("nameID");
**strikethrough starts here**
if (!sum && pnl.firstChild.tagName != "S" && pnl2.firstChild.tagname !="S")
{
pnl.innerHTML = "<S>"+ pnl.innerHTML+"</S>";
pnl2.innerHTML = "<S>"+ pnl2.innerHTML+"</S>";
}
else
{
pnl.innerHTML = pnl.firstChild.innerHTML;
pnl2.innerHTML = pnl2.firstChild.innerHTML;
}
}
</script>
it makes textstrikethrough but something is wrong. Even if i choose second checkbox it affects first checkbox why :(
http://jsfiddle.net/aHH9w/ (my full html page)
You are peforming a pretty convoluted way of achieving this, something that can actually be quite easily done. If you have an HTML element, say with the id 'myelement':
<div id="myelement">Hello world</div>
To create a strikethrough, all you need to do in JS is:
var ele = document.getElementById("myelement");
ele.style.setProperty("text-decoration", "line-through");
If you need to check if there is a strikethrough on an element:
var ele = document.getElementById("myelement");
var isStruck = (ele.style.getProperty("text-decoration") == "line-through");
Although this is not really recommended. Use an internal variable to keep track of state.