How to calculate content height by using pure javascript - javascript

I have used this code for defining "mainContent div height"
but it alerts undefined!
window.onload = function () {
alert(mainContent.height);
}
function viewPort() {
var pageWrapper = document.getElementById('pageWrapper').offsetHeight;
pageFooter = document.getElementById('pageFooter').offsetHeight;
pageHeader = document.getElementById('pageHeader').offsetHeight;
differenceInHeight = pageWrapper - (pageHeader + pageFooter);
mainContent = document.getElementById('mainContent').style.height = differenceInHeight + 'px';
};

Related

Change global variables by js function

I wanna change a group of scrolling images by clicking on button. question here is how to change the global variables by these function
please see the attached codes,
I wanna initiate the stack() function when onload and change the scrolling images set by onclick;
Should I add an onload event and seperately call the stack() funtions, only using the local var?
thanks,
Joe
var images = imagest;
function softtissue(){
var images = imagest;
}
function bone(){
var images = imagebone;
}
function lung(){
var images = imagelung;
}
var stack = new ImageStack({
images: images,
height: '512px',
width: '512px'
});
document.querySelector('.example').appendChild(stack);
// how to use the funciton on line 94
// for questions email felix#demont.is
var images10 = [
"https://igu3ss.files.wordpress.com/2012/09/chess_king_4.jpg",
"https://upload.wikimedia.org/wikipedia/commons/thumb/d/d3/Chess_piece_-_Black_queen.JPG/130px-Chess_piece_-_Black_queen.JPG", "https://asmoodle.asmadrid.org/blog/s16240/wp-content/uploads/sites/56/2014/12/protourney_knight_black_400.jpg",
"https://thumbs.dreamstime.com/x/chess-knight-white-background-29811348.jpg",
"http://cdn.craftsy.com/upload/3703789/pattern/115774/full_7439_115774_ChessKnightMachineEmbroideryDesign_1.jpg"
];
var imagesbone = [
"https://igu3ss.files.wordpress.com/2012/09/chess_king_4.jpg",
"https://upload.wikimedia.org/wikipedia/commons/thumb/d/d3/Chess_piece_-_Black_queen.JPG/130px-Chess_piece_-_Black_queen.JPG", "https://asmoodle.asmadrid.org/blog/s16240/wp-content/uploads/sites/56/2014/12/protourney_knight_black_400.jpg",
"https://thumbs.dreamstime.com/x/chess-knight-white-background-29811348.jpg",
"http://cdn.craftsy.com/upload/3703789/pattern/115774/full_7439_115774_ChessKnightMachineEmbroideryDesign_1.jpg",
"https://igu3ss.files.wordpress.com/2012/09/chess_king_4.jpg",
"https://upload.wikimedia.org/wikipedia/commons/thumb/d/d3/Chess_piece_-_Black_queen.JPG/130px-Chess_piece_-_Black_queen.JPG", "https://asmoodle.asmadrid.org/blog/s16240/wp-content/uploads/sites/56/2014/12/protourney_knight_black_400.jpg",
"https://thumbs.dreamstime.com/x/chess-knight-white-background-29811348.jpg",
"http://cdn.craftsy.com/upload/3703789/pattern/115774/full_7439_115774_ChessKnightMachineEmbroideryDesign_1.jpg"
];
var imageslung = [
"https://igu3ss.files.wordpress.com/2012/09/chess_king_4.jpg",
"https://upload.wikimedia.org/wikipedia/commons/thumb/d/d3/Chess_piece_-_Black_queen.JPG/130px-Chess_piece_-_Black_queen.JPG", "https://asmoodle.asmadrid.org/blog/s16240/wp-content/uploads/sites/56/2014/12/protourney_knight_black_400.jpg",
"https://thumbs.dreamstime.com/x/chess-knight-white-background-29811348.jpg",
"http://cdn.craftsy.com/upload/3703789/pattern/115774/full_7439_115774_ChessKnightMachineEmbroideryDesign_1.jpg",
"https://igu3ss.files.wordpress.com/2012/09/chess_king_4.jpg",
"https://upload.wikimedia.org/wikipedia/commons/thumb/d/d3/Chess_piece_-_Black_queen.JPG/130px-Chess_piece_-_Black_queen.JPG", "https://asmoodle.asmadrid.org/blog/s16240/wp-content/uploads/sites/56/2014/12/protourney_knight_black_400.jpg",
"https://thumbs.dreamstime.com/x/chess-knight-white-background-29811348.jpg",
"http://cdn.craftsy.com/upload/3703789/pattern/115774/full_7439_115774_ChessKnightMachineEmbroideryDesign_1.jpg",
"https://igu3ss.files.wordpress.com/2012/09/chess_king_4.jpg",
"https://upload.wikimedia.org/wikipedia/commons/thumb/d/d3/Chess_piece_-_Black_queen.JPG/130px-Chess_piece_-_Black_queen.JPG", "https://asmoodle.asmadrid.org/blog/s16240/wp-content/uploads/sites/56/2014/12/protourney_knight_black_400.jpg",
"https://thumbs.dreamstime.com/x/chess-knight-white-background-29811348.jpg",
"http://cdn.craftsy.com/upload/3703789/pattern/115774/full_7439_115774_ChessKnightMachineEmbroideryDesign_1.jpg"
];
function ImageStack(options) {
var self = this;
self.img_array = options.images;
self.stack = document.createElement('div');
self.stack.style.overflow = 'auto';
self.stack.style.maxWidth = '100%';
self.stack.style.height = options.height;
self.stack.style.width = options.width;
self.stack.style.backgroundSize = 'cover'
self.stack.style.position = 'relative';
var typeRegex = /(\D+)/
var sizeType = options.height.match(typeRegex)[0]
var numberRegex = /(\d+)/
self.height_number = Number(options.height.match(numberRegex)[0])
self.wrapper = document.createElement('div');
for (var i = 0; i < self.img_array.length; i++) {
var image = document.createElement('img');
image.src = self.img_array[i];
image.style.display = 'none';
image.style.position = 'absolute';
image.style.width = options.width;
image.style.height = options.height;
image.style.top = 0;
image.style.left = 0;
image.dataset.iid = i;
self.wrapper.appendChild(image);
}
self.image_elements = self.wrapper.querySelectorAll('img');
self.scrollobject = document.createElement('div');
self.scrollobject.style.width = '100%';
self.scrollobject.style.position = 'absolute';
self.scrollobject.style.zIndex = '2';
self.img_count = (self.img_array.length > 15) ? self.img_array.length : 15;
self.scrollobject_height = Math.floor(0.1 * self.img_count * self.height_number);
self.scrollobject.style.height = self.scrollobject_height + sizeType;
self.scrollUpdate = function(e) {
self.height_number = self.stack.getBoundingClientRect().height
self.scrollobject_height = Math.floor(0.1 * self.img_count * self.height_number);
var sT = self.stack.scrollTop
var hn05 = self.img_array.length - 1
var hh = (self.scrollobject_height - self.height_number) / hn05
scrollval = Math.floor(sT / (hh))
self.currentimg = self.image_elements[scrollval].src
self.stack.style.backgroundImage = 'url(' + self.currentimg + ')';
}
self.stack.addEventListener('scroll', self.scrollUpdate);
self.currentimg = self.image_elements[0].src
self.stack.style.backgroundImage = 'url(' + self.currentimg + ')';
window.addEventListener('resize', function() {
var stackRect = self.stack.getBoundingClientRect()
console.log(stackRect)
self.height_number = stackRect.height
self.scrollobject_height = Math.floor(0.1 * self.img_array.length * self.height_number);
self.stack.style.width = stackRect.width + 'px'
self.stack.style.eight = stackRect.width + 'px'
})
self.stack.appendChild(self.wrapper);
self.stack.appendChild(self.scrollobject);
return self.stack;
}
/*problems here*/
/*global var*/
var images = images10;
/*local var*/
function softtissue() {
var images = images10;
}
function bone() {
var images = imagesbone;
}
function lung() {
var images = imageslung;
}
/*how to switch the local var in global function*/
var stack = new ImageStack({
images: images,
height: '512px',
width: '512px'
});
document.querySelector('.example').appendChild(stack);
<div>
<button id="softtissue" type="button" onclick="softtissue();return false" class="button">
Soft Tissue</button>
<button id="bone" type="button" onclick="bone(); return false;" class="button">
Bone</button>
<button id="lung" type="button" onclick="lung(); return false" class="button">
Lung</button>
</div>
<div class="example">
</div>
var images = imagebone; never changes the global but it initializes a local variable. It creates a local variable images inside the function. You shouldn't use var inside functions
function softtissue(){
images = imagest;
}
function bone(){
images = imagebone;
}
function lung(){
images = imagelung;
}
A better approach would be to use images as a parameter to a general function instead of a separate function specific to the image. That way you can add unlimited amounts of images without the need to write an extra function for each image.
So inside the change_image() function, the correct image string just gets taken from the button clicked, instead of there being a function to set some global variable.
// ImageStack mockup
function ImageStack( config ) {
this.images = config.images;
this.height = config.height;
this.width = config.width;
}
ImageStack.prototype.node = function() {
return document.createElement( 'div' ).appendChild( document.createTextNode( this.images ));
};
// click event for all the buttons
function change_image( event ) {
var image_type = event.target.getAttribute( 'data-type' );
var stack = new ImageStack({
images: `image${ image_type }`,
height: '512px',
width: '512px'
});
render( stack.node() );
}
// render function.
// Could be inside the click event, but I would prefer seperate functions.
function render( image ) {
document.querySelector('.example').appendChild( image );
}
Array.from( document.querySelectorAll( 'button' )).forEach(function( button ) {
button.addEventListener( 'click', change_image );
});
<nav>
<button data-type="st">ST</button>
<button data-type="bone">BONE</button>
<button data-type="lung">LUNG</button>
</nav>
<section class="example"></section>
EDIT:
Since the question text got updated and no longer includes the line Or is there a better approach?, this answer might seem weird.
One approach is changing the varibility of the image
adding variability ="hidden" in the imagestack and after creating these three boxes, onclickfunction onlick choose which one to show

Resizing elements dynamically using javascript and the element.style attributes

I have tried searching for this but can't find any answers.
Details: I am trying to build a javascript carousel without using any libraries. My implementation is probably not the best. What I have decided to do is have a long div.carousel-track that contains many .carousel-items (these items are created from an object in javascript). The .carousel-track is wider than the page and has overflow: hidden on, so I can choose to have one item on the page at a time.
Because I am using bootstrap for the project in which it sits, I need it to align with bootstraps containers and columns. I do this by:
Getting the windows inner width, dividing by 12 and storing it.
When creating the .carousel-items I use this number to set the width and margins.
The probelm: This works initally, but when I try to resize the page and have the items resize too it will not, and instead stays with the old value. The variable that sets the width changes on resize, so why are the elements not when I re render them?
// Set global variables for the window.
var w = document.defaultView,
d = document,
e = document.documentElement,
g = d.getElementsByTagName('body')[0],
x = w.innerWidth || e.clientWidth || g.clientWidth,
y = w.innerHeight || e.clientHeight || g.clientHeight;
// Set the initial size of the bootstrap grid column for dynamic elements.
var colOne = x / 12;
window.addEventListener("optimizedResize", function () {
console.log('optimizedResize firing');
w = document.defaultView,
d = document,
e = document.documentElement,
g = d.getElementsByTagName('body')[0],
x = w.innerWidth || e.clientWidth || g.clientWidth,
y = w.innerHeight || e.clientHeight || g.clientHeight;
// Reset the size of bootsrap columns depending on the screen.
colOne = x / 12;
console.log(`x: ${x}, col-one: ${colOne}`);
view.infinite.resize();
});
var view = {
infinite: {
init: function () {
console.log(controller.getCurrentItem());
this.rightItem = controller.getRightItem();
this.centerItem = controller.getCurrentItem();
this.leftItem = controller.getLeftItem();
this.HTMLparentElement = document.createElement('div');
this.HTMLcarouselTrackElement = document.getElementById('carousel-track');
// Offset the carousel by 12 bootstrap columns (aka a whole page).
this.HTMLcarouselTrackElement.style.transform = "translateX(-" + colOne * 12 + "px)";
view.infinite.render();
},
render: function () {
console.log('rendering');
var carouselItems = [this.leftItem, this.centerItem, this.rightItem];
// Appends all the items in the carousel list in a row.
for (var i = 0; i < carouselItems.length; i++) {
this.HTMLcarouselItemContainer = document.createElement('div');
// Add classes for styling the carousel container.
this.HTMLcarouselItemContainer.classList.add('inner-carousel', 'carousel-item');
view.infinite.resize();
this.HTMLcarouselItemContainer.appendChild(HTMLprojectGradientOverlay);
// Append the whole carousel item to the carousel track.
this.HTMLparentElement.appendChild(this.HTMLcarouselItemContainer);
}
this.HTMLcarouselTrackElement.innerHTML = this.HTMLparentElement.innerHTML;
},
resize: function () {
// Dynamically set the width + margins to match the bootstrap width.
console.log(colOne);
this.HTMLcarouselItemContainer.style.width = (colOne * 10) + "px";
this.HTMLcarouselItemContainer.style.marginLeft = (colOne) + "px";
this.HTMLcarouselItemContainer.style.marginRight = (colOne) + "px";
console.log(this.HTMLcarouselItemContainer);
}
},
move: {
init: function () {
console.log('init move');
this.rbtn = d.createElement('button');
this.lbtn = d.createElement('button');
this.HTMLlistCellRight = document.createElement('li');
this.HTMLlistCellLeft = document.createElement('li');
this.HTMLspanIndicatorElemRight = document.createElement('span');
this.HTMLspanIndicatorElemLeft = document.createElement('span');
this.rbtn.innerText = "right";
this.lbtn.innerText = "left";
var HTMLindicatorListElem = document.getElementById('indicator-list');
this.HTMLspanIndicatorElemLeft.appendChild(this.lbtn);
this.HTMLlistCellLeft.appendChild(this.HTMLspanIndicatorElemLeft);
this.HTMLspanIndicatorElemRight.appendChild(this.rbtn);
this.HTMLlistCellRight.appendChild(this.HTMLspanIndicatorElemRight);
HTMLindicatorListElem.appendChild(this.HTMLlistCellLeft);
HTMLindicatorListElem.appendChild(this.HTMLlistCellRight);
this.rbtn.addEventListener('click', function () {
return function () {
controller.rightRotation();
view.infinite.init();
};
}());
this.lbtn.addEventListener('click', function () {
return function () {
controller.leftRotation();
view.infinite.init();
};
}());
view.move.render();
},
render: function () {
}
},
};

chrome extensions, trying to make minimize to tray button

I'm trying to use chrome app samples to make a chrome extensions that has a top custom top bar. I might have butcher the code but could someone help make it work?
https://github.com/GoogleChrome/chrome-app-samples/tree/master/samples/frameless-window
I can't make the minimize to tray button to work
function closeWindow() {
window.close();
}
function minimizeWindow() {
window.minimize();
}
function updateImageUrl(image_id, new_image_url) {
var image = document.getElementById(image_id);
if (image)
image.src = new_image_url;
}
function createImage(image_id, image_url) {
var image = document.createElement("img");
image.setAttribute("id", image_id);
image.src = image_url;
return image;
}
function createButton(button_id, button_name, normal_image_url,
hover_image_url, click_func) {
var button = document.createElement("div");
button.setAttribute("class", button_name);
var button_img = createImage(button_id, normal_image_url);
button.appendChild(button_img);
button.onmouseover = function() {
updateImageUrl(button_id, hover_image_url);
}
button.onmouseout = function() {
updateImageUrl(button_id, normal_image_url);
}
button.onclick = click_func;
return button;
}
function focusTitlebars(focus) {
var bg_color = focus ? "#3a3d3d" : "#000000";
var titlebar = document.getElementById("top-titlebar");
if (titlebar)
titlebar.style.backgroundColor = bg_color;
}
function addTitlebar(titlebar_name, titlebar_icon_url, titlebar_text) {
var titlebar = document.createElement("div");
var titlebar_name = "top-titlebar";
titlebar.setAttribute("id", titlebar_name);
titlebar.setAttribute("class", titlebar_name);
var icon = document.createElement("div");
icon.setAttribute("class", titlebar_name + "-icon");
icon.appendChild(createImage(titlebar_name + "icon", "16.png"));
titlebar.appendChild(icon);
var title = document.createElement("div");
title.setAttribute("class", titlebar_name + "-text");
title.innerText = document.title; // titlebar name
titlebar.appendChild(title);
var win = chrome.app.window.current();
var closeButton = createButton(titlebar_name + "-close-button",
titlebar_name + "-close-button",
"img/button_close.png",
"img/button_close_hover.png",
closeWindow);
titlebar.appendChild(closeButton);
// Create minimize button
var minimizeButton = createButton(titlebar_name + "-minimize-button",
titlebar_name + "-minimize-button",
"img/button_minimize.png",
"img/button_minimize_hover.png",
minimizeWindow);
titlebar.appendChild(minimizeButton);
//
var divider = document.createElement("div");
divider.setAttribute("class", titlebar_name + "-divider");
titlebar.appendChild(divider);
document.body.appendChild(titlebar);
}
function removeTitlebar(titlebar_name) {
var titlebar = document.getElementById(titlebar_name);
if (titlebar)
document.body.removeChild(titlebar);
}
function updateContentStyle() {
var content = document.getElementById("content");
if (!content)
return;
var left = 0;
var top = 0;
var width = window.outerWidth;
var height = window.outerHeight;
var titlebar = document.getElementById("top-titlebar");
if (titlebar) {
height -= titlebar.offsetHeight;
top += titlebar.offsetHeight;
}
if (titlebar) {
width -= titlebar.offsetWidth;
}
var contentStyle = "position: absolute; ";
contentStyle += "left: " + left + "px; ";
contentStyle += "top: " + top + "px; ";
contentStyle += "width: " + width + "px; ";
contentStyle += "height: " + height + "px; ";
content.setAttribute("style", contentStyle);
}
This will fix the problem
function minimizeWindow() {
var window = chrome.app.window.current();
window.minimize();
}

Changes to Javascript created element doesn't reflect to DOM

I have a class, that is supposed to display grey overlay over page and display text and loading gif. Code looks like this:
function LoadingIcon(imgSrc) {
var elem_loader = document.createElement('div'),
elem_messageSpan = document.createElement('span'),
loaderVisible = false;
elem_loader.style.position = 'absolute';
elem_loader.style.left = '0';
elem_loader.style.top = '0';
elem_loader.style.width = '100%';
elem_loader.style.height = '100%';
elem_loader.style.backgroundColor = 'rgba(0, 0, 0, 0.5)';
elem_loader.style.textAlign = 'center';
elem_loader.appendChild(elem_messageSpan);
elem_loader.innerHTML += '<br><img src="' + imgSrc + '">';
elem_messageSpan.style.backgroundColor = '#f00';
this.start = function () {
document.body.appendChild(elem_loader);
loaderVisible = true;
};
this.stop = function() {
if (loaderVisible) {
document.body.removeChild(elem_loader);
loaderVisible = false;
}
};
this.setText = function(text) {
elem_messageSpan.innerHTML = text;
};
this.getElems = function() {
return [elem_loader, elem_messageSpan];
};
}
Problem is, when I use setText method, it sets innerHTML of elem_messageSpan, but it doesn't reflect to the span, that was appended to elem_loader. You can use getElems method to find out what both elements contains.
Where is the problem? Because I don't see single reason why this shouldn't work.
EDIT:
I call it like this:
var xml = new CwgParser('cwg.geog.cz/cwg.xml'),
loader = new LoadingIcon('./ajax-loader.gif');
xml.ondataparse = function() {
loader.stop();
document.getElementById('cover').style.display = 'block';
};
loader.setText('Loading CWG list...');
loader.start();
xml.loadXML();
xml.loadXML() is function that usually takes 3 - 8 seconds to execute (based on download speed of client), thats why I'm displaying loading icon.

Javascript JQUERY Media Player Duration Issues

So, I've been working on an mp3 player that doesn't use Flash, just JS, HTML, and CSS. I took some open source code and have been playing with it, however I had to edit it when I started using JSONP to get the "link" of the MP3 file from another website. I had issues getting any of the JS function calls in the HTML to work, so I used JQUERY bind and that fixed everything but duration function and clientx issues. link = foo.mp3
function writePlayer(link){
$('<div id=\"main\"><h2>Episode</h2><div id=\"player\"><input id=\"playButton\" class=\'player_control\' type=\"button\" onClick=\"playClicked(this);\" value=\">\"><div id=\"duration\" class=\'player_control\' ><div id=\"duration_background\" onClick=\"durationClicked(event);\"><div id=\"duration_bar\" class=\'duration_bar\'></div></div></div><div id=\"volume_control\" class=\'player_control\' onClick=\"volumeChangeClicked(event);\"><div id=\"volume_background\"><div id=\"volume_bar\"></div></div></div><input type=\"button\" class=\'player_control\' id=\"volume_button\" onClick=\"volumeClicked();\" value=\"Vol\"></div><audio id=\"aplayer\" src='+ link +' type=\"audio/mp3\" onTimeUpdate=\"update();\" onEnded=\"trackEnded();\"><b>Your browser does not support the <code>audio</code> element. </b></audio><div id=\"msg\" class=\'output\'></div><div id=\"content\"><p></p></div></div></div>').appendTo('body');
$(document).ready(pageLoaded)
$("#playButton").bind('click',playClicked(this))
$("#duration_background").bind('click',durationClicked(event))
$("#volume_control").bind('click',volumeChangeClicked(event))
$("#volume_button").bind('click',volumeClicked(event))
$("#aplayer").bind('timeUpdate',update())
$("#aplayer").bind('ended',trackEnded())
};
var audio_duration;
var audio_player;
var volume_button;
var volume_control;
function pageLoaded()
{
audio_player = document.getElementById("aplayer");
alert(audio_player);
volume_button = document.getElementById('volume_button');
volume_control = document.getElementById('volume_control');
//get the duration
audio_duration = audio_player.duration;
//set the volume
set_volume(0.7);
}
function set_volume(new_volume)
{
audio_player.volume = new_volume;
update_volume_bar();
volume_button.value = "Volume: "+parseInt(new_volume*100);
}
function update_volume_bar()
{
new_top = volume_button.offsetHeight - volume_control.offsetHeight;
volume_control.style.top = new_top+"px";
volume = audio_player.volume;
//change the size of the volume bar
wrapper = document.getElementById("volume_background");
wrapper_height = wrapper.offsetHeight;
wrapper_top = wrapper.offsetTop;
new_height= wrapper_height*volume;
volume_bar = document.getElementById("volume_bar");
volume_bar.style.height=new_height+"px";
new_top = wrapper_top + ( wrapper_height - new_height );
volume_bar.style.top=new_top+"px";
}
function update(audio_player)
{
//get the duration of the player
dur = audio_player.duration;
time = audio_player.currentTime;
fraction = time/dur;
percent = (fraction*100);
wrapper = document.getElementById("duration_background");
new_width = wrapper.offsetWidth*fraction;
document.getElementById("duration_bar").style.width=new_width+"px";
}
function playClicked(element)
{
//get the state of the player
if(audio_player.paused)
{
audio_player.play();
newdisplay = "| |";
}else{
audio_player.pause();
newdisplay = ">";
}
element.value=newdisplay;
}
function trackEnded()
{
//reset the playControl to 'play'
document.getElementById("playButton").value=">";
}
function volumeClicked(event)
{
control = document.getElementById('volume_control');
if(control.style.display=="block")
{
control.style.display="None";
}else{
control.style.display="Block";
update_volume_bar();
}
}
function volumeChangeClicked(event)
{
//get the position of the event
clientY = event.clientY;
offset = event.currentTarget.offsetTop + event.currentTarget.offsetHeight - clientY;
volume = offset/event.currentTarget.offsetHeight;
set_volume(volume);
update_volume_bar();
}
function durationClicked(event)
{
//get the position of the event
clientX = event.clientX;
left = event.currentTarget.offsetLeft;
clickoffset = clientX - left;
percent = clickoffset/event.currentTarget.offsetWidth;
duration_seek = percent*audio_duration;
document.getElementById("aplayer").currentTime=duration_seek;
};
</script>
Thank you very much for your help!

Categories

Resources