I want to change the padding on my header so that it effectively is lowered onto the page. I have the following code which runs and does nothing:
function openPage() {
var i, el = document.getElementById('headbar');
for(i=0;i<30;i++) {
el.style.paddingTop = el.style.paddingTop + 1;
}
}
However, while trying to figure out why it wasn't working in the console I figured out that maybe it is because the padding must be written in pixels because the following works and changes the padding in the console:
document.getElementById('headbar').style.paddingTop='100px';
is there any way I could do this without Jquery and without having to make a substring and reconcatonating?
Try appending px to the variable
var fontSize = parseInt(el.style.paddingTop, 10);
el.style.paddingTop = ( (!isNaN(fontSize) : fontSize : 0) + 1) + 'px';
Pretty simple just do this:
for(i=0;i<30;i++) {
var px = (el.style.paddingTop + 1) + "px";
el.style.paddingTop = px;
}
Related
As a self-improvement exercise I am building a piece of plain js that takes a set of various sized squares (all of the same aspect ratio) and lays them out in a fluid grid so that there are no gaps.
After spending the evening I have a very basic model that works for the test data I have given it.
The last problem I need to solve before I can justify sinking more time in it is this:
When resizing the browser window the width of the parent element (#container) is not being re calculated.
This width is being used with the aspect ratio of the grid items to calculate the row height so when you resize the window everything shifts correctly except the vertical position.
The function being called by window.onresize is as follows
function() {
var parentElem = this.element;
console.log(parentElem.offsetWidth);
var elems = parentElem.getElementsByTagName('*'), i;
for (i in elems) {
if((' ' + elems[i].className + ' ').indexOf(' ' + 'tile' + ' ') > -1) {
var ele = elems[i];
var tile_size = ele.getAttribute('data-grid-size');
var tile_col = ele.getAttribute('data-grid-col');
var tile_row = ele.getAttribute('data-grid-row');
var col_width = (100 / this.options.cols); // column width in %
var row_height = (parentElem.getElementWidth() / this.options.cols) / this.options.tile_ratio;
var left_offset = col_width * tile_col;
var top_offset = row_height * tile_row;
// Position tiles
var currentStyle = ele.getAttribute('style');
ele.setAttribute('style', currentStyle + ' left: ' + left_offset + '%; top: ' + top_offset + 'px;');
}
}
}
See the full fiddle here.
So any ideas as to why the width of the element is not being recalculated?
This line from your fiddle:
window.onresize = gridfill.layoutGrid();
...doesn't assign your function as a resize handler, it calls your function immediately and tries to assign the return value as a resize handler. You need to remove the parentheses:
window.onresize = gridfill.layoutGrid;
Except to keep the correct context within the function you will need to use:
window.onresize = gridfill.layoutGrid.bind(gridfill);
Note that the .bind() function is not supported by IE<=8, but you can use a polyfill, or just wrap the function call:
window.onresize = function() { gridfill.layoutGrid(); };
Demo: http://jsfiddle.net/WzaXF/1/
I want to increase the height of the div tag on click of button. Every time a user clicks a button it should increase the height of that particular div tag, say by 200px or so..
HTML
<div id="controls">
<input type="button" onclick="incHeight()" id="btn" name="btn">
</div>
<div id="container" style="min-height:250px;"> </div>
The below script works properly
Javascript
<script type="text/javascript">
function incHeight()
{
document.getElementById("container").style.height = 250+'px';
}
</script>
But I want to do something like this, which is not working. The problem I think is the 'px' portion in the value. Anybody have any idea how to extract the INT portion of the value...
<script type="text/javascript">
function incHeight()
{
document.getElementById("container").style.height += 250;
}
</script>
The problem is how do I get the '250' portion of the height value neglecting the 'px' in javascript..
Try this:
function incHeight() {
var el = document.getElementById("container");
var height = el.offsetHeight;
var newHeight = height + 200;
el.style.height = newHeight + 'px';
}
Fiddle
Try something like
var container = document.getElementById('container');
container.style.height = (container.offsetHeight + 250) + "px";
In case offsetHeight is not working, try parsing the style.height for its numeric value instead.
var currentHeight = (container.style.height) ? (parseInt(container.style.height.match(/[0-9]+/)[0]) : container.offsetHeight;
Also, simply parseInt(container.style.height) might work
Try this:
getElementById('container').setAttribute("style","height:500px");
or
function resize(element) {
var height = 0;
var body = window.document.body;
if (window.innerHeight) {
height = window.innerHeight;
} else if (body.parentElement.clientHeight) {
height = body.parentElement.clientHeight;
} else if (body && body.clientHeight) {
height = body.clientHeight;
}
element.style.height = ((height - element.offsetTop) + "px");
}
You can use a regular expression to only keep the numbers in the string:
var style = document.getElementById("container").style;
style.height = style.height.replace( /^\D+/g, '') + 'px';
I am creating a new "whack-a-mole" style game where the children have to hit the correct numbers in accordance to the question.
I have the numbers animating from a set top position to another with a random width so that they look like they are floating up like bubbles.
The only problem I am having with it is that sometimes the numbers glitch and the width on them changes suddenly making it appear to jump from one side of the container to the other.
The only explanation I can think of is the width must be resetting somewhere which I have tried to look for.
Either I am blind or it is something else, can someone help me to find the source of the problem.
Here is the code that maps the numbers...
function randomFromTo(from, to) {
return Math.floor(Math.random() * (to - from + 1) + from);
}
function scramble() {
var children = $('#container').children();
var randomId = randomFromTo(1, children.length);
moveRandom("char" + randomId);
}
function moveRandom(id) {
var cPos = $('#container').offset();
var cHeight = $('#container').height();
var cWidth = $('#container').width();
var bWidth = $('#' + id).width();
var bHeight = $('#' + id).css(
'top', '400px'
).fadeIn(1000).animate({
' top': '-100px'
}, 10000).fadeOut(1000);
maxWidth = cPos.left + cWidth - bWidth;
minWidth = cPos.left;
newWidth = randomFromTo(minWidth, maxWidth);
$('#' + id).css({
left: newWidth
}).fadeIn(1000, function () {
setTimeout(function () {
$('#' + id).fadeOut(1000);
window.cont++;
}, 1000);
});
Here is also a working fiddle so you can see the issue I am talking about: http://jsfiddle.net/pUwKb/26/
The problem is that you are re-entering your moveRandom function for an ID that is already animated. The new width calculation causes the piece to seem to jump when it is reassigned during the already animated movement. One way to fix this is to reject new piece movements for pieces you are already animating. I modified your jsFiddle and fixed it with this code:
// Keep track of the pieces actually moving
var currentMoving = [];
function moveRandom(id) {
// If this one's already animating, skip it
if ($.inArray(id, currentMoving) !== -1) {
return;
}
// Mark this one as animating
currentMoving.push(id);
var cPos = $('#container').offset();
var cHeight = $('#container').height();
var cWidth = $('#container').width();
var bWidth = $('#' + id).width();
var bHeight = $('#' + id).css('top', '400px').fadeIn(1000).animate({
'top': '-100px'
}, 10000).fadeOut(1000);
maxWidth = cPos.left + cWidth - bWidth;
minWidth = cPos.left;
newWidth = randomFromTo(minWidth, maxWidth);
$('#' + id).css({
left: newWidth
}).fadeIn(1000, function () {
setTimeout(function () {
$('#' + id).fadeOut(1000);
// Mark this as no longer animating
var ix = $.inArray(id, currentMoving);
if (ix !== -1) {
currentMoving.splice(ix, 1);
}
window.cont++;
}, 1000);
});
}
Forked jsFiddle here.
Edit: The OP wanted to show more divs at once without speeding the animation up. To do this I added 20 more character divs (each a duplicate of the first 10 numbers), fixed the guarding code a bit, altered the CSS to specify the image of the character by class, and then put a limit of 20 animations at a given time. I also put a loop around the rejection of an already animated piece, to pick another. I made some other minor improvements. Updated JSFiddle here.
Here I tried to make simple zoom in and out functions on button click.
HTML
<input type="button" value ="-" onClick="zoom(0.9)"/>
<input type="button" value ="+" onClick="zoom(1.1)"/>
<div id="thediv">
<img id="pic" src="http://cdn1.iconfinder.com/data/icons/VistaICO_Toolbar-Icons/256/Zoom-in.png"/>
</div>
SCRIPT
var zoomLevel = 100;
var maxZoomLevel = 105;
var minZoomLevel = 95;
function zoom(zm) {
var img=document.getElementById("pic");
if(zm > 1){
if(zoomLevel < maxZoomLevel){
zoomLevel++;
}else{
return;
}
}else if(zm < 1){
if(zoomLevel > minZoomLevel){
zoomLevel--;
}else{
return;
}
}
wid = img.width;
ht = img.height;
img.style.width = (wid*zm)+"px";
img.style.height = (ht*zm)+"px";
img.style.marginLeft = -(img.width/2) + "px";
img.style.marginTop = -(img.height/2) + "px";
}
But the problem is, whenever I click the zoom-in function the image moves to the top corner of the page. I tried to solve this but no solution was effective.
Here is the BIN I am working on which may be useful to find my mistake.
And also another question: Is there a way to apply mousewheel to this function?
UPDATE
The problem of zoom has been changed. But now the mousewheel also done here but the problem is we can't give the maximum value for the mousewheel.
UPDATED BIN
img.style.marginLeft = -(img.width/2) + "px"; // you have negation sign here
img.style.marginTop = -(img.height/2) + "px"; // you have negation sign here
Change it TO :
img.style.marginLeft = (img.width/2) + "px";
img.style.marginTop = (img.height/2) + "px";
JS BIN LINK
Judging by your marginLeft and marginTop calculation, I guess that you want to zoom in and out of the image while preserving the center point.
So try this:
http://jsbin.com/itekek/4
Preserved an initial width and height value, and slightly modified the zoom limit value.
Edit:
http://jsbin.com/itekek/46
Added mouse wheel support.
See this : http://jsbin.com/itekek/14/edit
You have unstripped zoom plus Mousewheel here..
Update: To get elements by class name use function below:
function findElementByClass(matchClass) {
var elems = document.getElementsByTagName('*'),i;
for (i in elems) {
if ((" " + elems[i].className + " ").indexOf(" " + matchClass + " ") > -1) {
return elems[i];
}
}
return null;
}
See sample
Is it possible to know whether or not an HTML element like image is viewable in current viewport or it will be visible on scroll?
If it is viewable completely or partially then how can I get the amount of portions is visible?
I am trying to explain it from the following image:
The two images at the bottom is partially visible within the viewport and these will be completely visible if one scroll down a little bit.
Now I want to get the the aforesaid information.
In the actual scenario I am trying to get the popup-zoom effect on hover of image in my album like google image search. Everything is fine, except if the images are placed in the described manner then the zoomed div also displaying in half.
Normal condition where image is completely in viewport:
And partially in viewport:
I really appreciate your help.
The code:
var albumDetailOnReady = function() {
$('.image').each(function(){
var photo = $(this);
var wrap = $(findParentByClassName(document.getElementById(photo.attr('id')), 'wrap'));
var row = $(findParentByClassName(document.getElementById(wrap.attr('id')), 'albumDetailRow'));
var visibleZone = $(wrap).find('.alDtlColumn');
var pictureBlock = $(visibleZone).find('.pictuteBlock');
var hiddenZone = $(wrap).find('.hiddenZone');
$(photo).load(function(){
if(177 > $(photo).width()){
var imgleft = ($(pictureBlock).width() - $(photo).width())/2 + 'px';
$(photo).css({'left': imgleft});
}
});
$(photo).hover(function(){
var y;
if($(photo).height() > $(photo).width()) {
y = ($(visibleZone).offset().top - 50) + 'px';
} else {
y = ($(visibleZone).offset().top + 50) + 'px';
}
var x;
if($(row).find('.wrap:first').attr('id') === $(wrap).attr('id')) {
x = ($(visibleZone).offset().left - 10) + 'px';
} else if($(row).find('.wrap:last').attr('id') === $(wrap).attr('id')) {
x = ($(visibleZone).offset().left - 50) + 'px';
} else {
x = ($(visibleZone).offset().left - 20) + 'px';
}
$(hiddenZone).css({
'top': y,
'left': x,
'position': 'absolute',
'z-index': '10'
});
$(hiddenZone).fadeIn('fast');
}, function(){
});
$(hiddenZone).hover(function(){},function(){
$(hiddenZone).hide().stop(true, true);
});
});
}
var findParentByClassName = function(element, clazz) {
while (element.parentNode) {
element = element.parentNode;
if (hasClass(element, clazz)) {
return element;
}
}
return null;
}
function hasClass(element, cls) {
var regex = new RegExp('\\b' + cls + '\\b');
return regex.test(element.className);
}
I am unable to show any HTML as I haven't have any, I am working in ADF framework.
But for an explanation:
I have two zone for each image: visible and hidden. Both of them are in a wrap. Now on hover an image I am showing the hidden div. The top and left of the hidden div is measured by the top and left of the visible div with some condition.
jQuery.Viewport
Very helpfull and lightweight jQuery plugin that makes an element as a handy viewport for displaying elements with absolute position. The plugin is hosted on GitHub. You can see it in action right there:
https://github.com/borbit/jquery.viewport