Understanding Javascript InnerHTML property - javascript

Recently I run into a scenario, which i trying to understand. I whave already got workaround and my job is done but i am still not able to understand why the scenarion actually occured. Problem is strictly programming based so i hope it is allowed on stackoverflow.
I had a Div on a page:
<DIV id="tos3" >
<FONT size=2 face=Arial color=#009a00><B>How to request Business Applications Software </B></FONT>
<BR/><BR/>
<FONT size=2 face=Arial color=#000000>
<select id="segment" onchange="getSecondDropdown(this);"><option value="Segment">Select Segment</option>
<option value="E&P">E&P</option>
<option value="R&M">R&M</option>
<option value="IST">IST</option>
<option value="Functions">Functions</option>
<option value="Other">Other</option>
</select>
<select id="DivisionDP" disabled="disabled" onchange="getDetails();"><option value="Division">Select Division/SPU/Region</option>
</select>
<DIV id="infoDetails"></DIV>
</FONT>
</DIV>
Related Javascript:
function getSecondDropdown(e)
{
// get the values in seconnd drop down
}
function getDetails()
{
// display details based on selection
}
It was working fine on the page.
Than came a request to display this div on Popup.
We have a popup code in our master page, which is being used through our site to display data:
<div id="testDiv" style="border-left:2px solid #99cc00;border-right:2px solid #99cc00;border-top:2px solid #4c4c4c;border-bottom:2px solid #4c4c4c;width:500px;display:none;background-color: #eeeeee;z-index:1000;padding:10px 10px 10px 10px">
<div align="right" style="height:25 px;">
<a style="cursor:pointer" onClick="closePouUp()">close</a>
</div>
<div id="contentDiv" style="overflow:auto;"> testDiv content</div>
</div>
<div id="greyout" style="background-color: black; display:none;z-index:400;filter: alpha(opacity=70);opacity: 0.7;width:100%; height:100%;">
</div>
function ShowHideProduct(sValue,flag)
{
var customCopyrightContainer;
customCopyrightContainer = document.getElementById(sValue);
divRef = document.getElementById('testDiv');
innerDiv=document.getElementById('contentDiv');
if(flag==1)
{
innerDiv.style.height = "300px";
}
innerDiv.innerHTML= customCopyrightContainer.innerHTML;
// Get the screen dimensions...
var screenSize = getViewportSize();
var screenWidth = screenSize.width;
var screenHeight = screenSize.height;
// Get the element dimensions...
var elementSize = getElementSize(divRef);
var elementWidth = elementSize.width;
var elementHeight = elementSize.height;
// Calculate the centering positions...
var xPos = (screenWidth - elementWidth) / 2;
var yPos = (screenHeight - elementHeight) / 2;
yPos=document.body.scrollTop/2+yPos;
var body = document.body,
html = document.documentElement;
var height = Math.max( body.scrollHeight, body.offsetHeight,
html.clientHeight, html.scrollHeight, html.offsetHeight );
//make page greyout
greyOutDiv=document.getElementById('greyout');
greyOutDiv.style.position = 'absolute';
greyOutDiv.style.left = '0px';
greyOutDiv.style.top = '0px';
greyOutDiv.style.width = '1500px';
greyOutDiv.style.height = height + 'px';
greyOutDiv.style.display = 'block';
// Position the element...
divRef.style.position = 'absolute';
divRef.style.left = xPos + 'px';
divRef.style.top = yPos + 'px';
divRef.style.display = 'block';
if(flag==1)
{
divRef.style.height = "300px";
}
return;
}
function closePouUp()
{
divRef = document.getElementById('testDiv');
greyOutDiv=document.getElementById('greyout');
divRef.style.display = 'none';
greyOutDiv.style.display = 'none';
}
I used the same code and functionality was not working.
From the output i felt like that the javasript innerHTML thing is creating a temporary objects. I felt this because the first dropdown was not working with getElementByID method but when i passed its refrence in the method it worked.
I did not get any proper explation of this.
I have fixed my problem by showing the original div as popup. So now i am just trying to understand what exactly happend.

Related

Changing image size using input and buttons

I want to change the size of an image with an input and buttons.
I have an input, to which i insert the desired size, an image and 2 buttons.
One for making the image size change according to the input ( for example, if the user typed 300 in the input, the image width and height, will both change to 300px).
And one for making the image size double itself, by clicking the other button.
javascript :
var myImg = document.getElementById("myImg")
var input = document.getElementById("insert")
function increaseSize()
{
input.value = myImg.size.width
input.value = myImg.size.height
}
function doubleSize()
{
myImg.style.width * 2
myImg.style.height * 2
}
It didn't work.
You've got errors in your code. The first thing I can see is in the increaseSize() function, you are assigning the value to the input, not the image.
input.value = myImg.size.width
This line means that you have taken the width of the image and inserted that value into your input, which is the opposite of what you want to do. You want to take the value in your input and inject it into the images style.width property. So for starters, change that function (also there is no .size property, you wanted .style:
// option 1 create within function
function increaseSize() {
var myImg = document.getElementById( "myImg" );
myImg.style.width = input.value;
myImg.style.height = input.value;
}
// option 2 pass as parameters
var myImg = document.getElementById( "myImg" ); // assign the variables
var input = document.getElementById( "size" );
function increaseSize( img, input ) { // create the function
img.style.width = input.value + 'px'; // assign a unit type to it, as it is a css value
img.style.height = input.value + 'px';
}
increaseSize( myImg ); // run the function, passing in our variables
You have to use style to assign width and height using CSS, please find below example, where I have used the button to change the size, you can do it with input field as well:
document.getElementById("go").addEventListener("click", function() {
var img = document.querySelectorAll("#container .image img")[0];
img.style.height = "200px";
img.style.width = "200px";
});
div#container {
width: 100%;
height: 100%;
}
div.image img {
position:fixed;
width: 100px;
height: 100px;
}
<button id="go">Increase</button>
<div id="container">
<div class="image"><img src="http://libcom.org/files/images/library/black-square.jpg"/></div>
</div>
The width and height properties return string with px appended to it so remove the px part convert it to number and multiply it by 2.
var myImg = document.getElementById("myImg")
var input = document.getElementById("insert")
function increaseSize() {
myImg.style.width = input.value + 'px';
myImg.style.height = input.value + 'px';
}
function doubleSize() {
myImg.style.width = Number(myImg.style.width.slice(0,-2)) * 2 + 'px';
myImg.style.height = Number(myImg.style.height.slice(0,-2)) * 2 + 'px';
}
Try this
function changeSize(){
console.log('Clikced change size!');
var size=parseInt(document.querySelector('#img_size').value);
var img=document.querySelector('#img');
img.width=size;
img.height=size;
}
function doubleSize(){
console.log('Clikced double size!');
var img=document.querySelector('#img');
var size=parseInt(img.width)*2;
img.width=size;
img.height=size;
}
<img src='http://placehold.it/120x120&text=image1' width='200px' height="200px" id="img">
<input type="number" id='img_size' >
<button id="change_size" onclick="changeSize()"> Change Size</button>
<button id="double_size" onclick="doubleSize()">Double Size</button>

Screen following the "character"

I'm trying to achieve the following image,
Then whenever the player moves (he moves by click) I want the visible area to move with him. the visible area should be displayed over the whole screen.
I've currently got the following code but I have no idea how to make it so just the visible area is visible;
Code
<body>
<div class="map">
<div class="screen">
<div class="player">
<img class="ship" src="https://vignette.wikia.nocookie.net/darkorbit/images/a/a9/Neuergoli.jpg/revision/latest?cb=20120819231510">
</div>
</div>
</div>
</body>
$(function(){
$('.map .screen').on('click', function(event){
var clickedPosX = event.pageX,
clickedPosY = event.pageY;
var $player = $('.screen');
$player.animate({left:clickedPosX, top:clickedPosY}, 1000);
});
});
JSFiddle
try this one
$(function(){
var $map = $(".map");
var $player = $('.player');
var centerPlayerX = $player.offset().left + $player.width() / 2;
var centerPlayerY = $player.offset().top + $player.height() / 2;
$('.map').on('click', function(event){
var clickedPosX = event.pageX,
clickedPosY = event.pageY;
var currentMapPositionX = parseFloat($map.css("background-position-x"));
var currentMapPositionY = parseFloat($map.css("background-position-y"));
var moveMapX = currentMapPositionX - clickedPosX + centerPlayerX;
var moveMapY = currentMapPositionY - clickedPosY + centerPlayerY;
$map.animate({ "background-position-x": `${moveMapX}px`, "background-position-y": `${moveMapY}px` }, 1000);
});
});
and add background-repeat: repeat; to .map css

Get cursor writing positions

Is it possible to get the positions of cursor of writing (absolute x,y pixels positions of the last character) inside the input textarea
Note: its not just count number of characters, but I have to deal with new lines, for example, if the user type the Enter key (I have to detect the new position in pixels of the last character
I want this because i need to display a popup with suggestions while users type texts
if you have an example in reactjs or in classic javascript (not jquery) please share with your code
i hope that my question was clear.
Thank you in advance
Finally i found a solution:
here the code for reactjs
var text = this.refs.areatext,
coords = {};
var carPos = text.selectionEnd,
div = document.createElement("div"),
span = document.createElement("span"),
copyStyle = getComputedStyle(text);
[].forEach.call(copyStyle, function(prop){
div.style[prop] = copyStyle[prop];
});
div.style.position = "absolute";
document.body.appendChild(div);
div.textContent = text.value.substr(0, carPos);
span.textContent = text.value.substr(carPos) || ".";
div.appendChild(span);
coords = {
"TOP": span.offsetTop,
"LEFT": span.offsetLeft
};
document.body.removeChild(div);
this.setState({x:coords.LEFT,y:coords.TOP})
for javascript
(function() {
var text = document.querySelector(‘textarea’),
indicator = document.querySelector(‘.indicator’),
getCoord = function(e) {
var carPos = text.selectionEnd,
div = document.createElement(‘div’),
span = document.createElement(‘span’),
copyStyle = getComputedStyle(text),
coords = {};
[].forEach.call(copyStyle, function(prop){
div.style[prop] = copyStyle[prop];
});
div.style.position = ‘absolute’;
document.body.appendChild(div);
div.textContent = text.value.substr(0, carPos);
span.textContent = text.value.substr(carPos) || ‘.’;
div.appendChild(span);
coords = {
‘TOP’: span.offsetTop,
‘LEFT’: span.offsetLeft
};
console.log(coords);
indicator.style.left = coords.LEFT + ‘px’;
indicator.style.top = coords.TOP + ‘px’;
document.body.removeChild(div);
};
text.addEventListener(‘input’, getCoord);
}());
Please check this code, i have made cursor detection in javascript, hope will help you.
window.onload = init;
function init() {
if (window.Event) {
document.captureEvents(Event.MOUSEMOVE);
}
document.onmousemove = getCursorXY;
}
function getCursorXY(e) {
document.getElementById('cursorX').value = (window.Event) ? e.pageX : event.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
document.getElementById('cursorY').value = (window.Event) ? e.pageY : event.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
}
<html>
<body>
<input type="text" id="cursorX" size="3"> X-position of the mouse cursor
<br /><br />
<input type="text" id="cursorY" size="3"> Y-position of the mouse cursor
</body>
</html>

Merge Javascript function to maintain postback with a fixed header

My goal is to have a GridView inside a div have the fixed header work as well as maintain scroll position after postback. I have two functions that work separately, but as I know little about Javascript syntax, I am having trouble merging the functions. Can someone help me out? Thanks!
Relevant code:
<script language="javascript" type="text/javascript"> //FUNCTION 1 Static Header
function MakeStaticHeader(gridId, height, width, headerHeight, isFooter) {
var tbl = document.getElementById(gridId);
if (tbl) {
var DivHR = document.getElementById('DivHeaderRow');
var DivMC = document.getElementById('DivMainContent');
var DivFR = document.getElementById('DivFooterRow');
//*** Set divheaderRow Properties ****
DivHR.style.height = headerHeight + 'px';
DivHR.style.width = (parseInt(width) - 0) + 'px';
DivHR.style.position = 'relative';
DivHR.style.top = '0px';
DivHR.style.zIndex = '10';
DivHR.style.verticalAlign = 'top';
DivHR.style.alignContent = 'center';
//*** Set divMainContent Properties ****
DivMC.style.width = width + 'px';
DivMC.style.height = height + 'px';
DivMC.style.position = 'relative';
DivMC.style.top = -headerHeight + 'px';
DivMC.style.zIndex = '1';
//****Copy Header in divHeaderRow****
DivHR.appendChild(tbl.cloneNode(true));
}
}
function OnScrollDiv(Scrollablediv) {
document.getElementById('DivHeaderRow').scrollLeft = Scrollablediv.scrollLeft;
}
</script>
<script type="text/javascript"> // FUNCTION 2 Maintain Scroll
window.onload = function () {
var h = document.getElementById("<%=hfScrollPosition.ClientID%>");
document.getElementById("<%=DivMainContent.ClientID%>").scrollTop = h.value;
}
function SetDivPosition() {
var intY = document.getElementById("<%=DivMainContent.ClientID%>").scrollTop;
var h = document.getElementById("<%=hfScrollPosition.ClientID%>");
h.value = intY;
}
function afterpostback() {
var h = document.getElementById("<%=hfScrollPosition.ClientID%>");
document.getElementById("<%=DivMainContent.ClientID%>").scrollTop = h.value;
}
</script>
<asp:HiddenField ID="hfScrollPosition" runat="server" Value="0" />
<div style="overflow: hidden;" id="DivHeaderRow"></div>
<div style="overflow: scroll;" onscroll="SetDivPosition()" id="DivMainContent" runat="server">
<asp:GridView ID="GridView1" runat="server" DataKeyNames="ID" AutoGenerateColumns="True" ....> </asp:GridView>
</div>
A HUGE simple fix. Just added
<div style="overflow: scroll;" onscroll="SetDivPosition(); OnScrollDiv(this)" id="DivMainContent" runat="server">
Focusing specifically on OnScrollDiv(this) added in the function. Works like a charm.

How to have div re-size itself to image on page load

So my goal is to have an image slideshow with 3 clickable hot spots at the bottom. I have the basic functionality of this down now, but my content div doesn't size itself properly until it loops through the images for the first time. I need everything to be sized and positioned correctly immediately when the page loads.
<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#image").attr("src", images[0]);
});
//Click tracking
var badClicks = 0;
var skipClicks = 0;
var goodClicks = 0;
//Counter to keep track of images
var iCount = 0;
var images = [];
images[0] = "images/document.png";
images[1] = "images/document2.png";
images[2] = "images/document3.png";
function nextImage(){
iCount++;
//If there are no more images in the array, go back to the first image
if (images[iCount]==null) {
iCount = 0;
};
//Change image source to new image
$("#image").attr("src", images[iCount]);
//Set content wrapper width & height to current image's width & height
$("#content").css("width", $("#image").css("width"));
$("#content").css("height", $("#image").css("height"));
//Store content wrapper's new width and height into variables
var h = parseInt($("#content").css("height"));
var w = parseInt($("#content").css("width"));
//Move hotspot-wrapper to the bottom of the new image
//Height of content wrapper - height of hotspot wrapper = new top
$("#hotspot-wrapper").css("top", h - parseInt($("#hotspot-wrapper").css("height")));
console.log(images[iCount] + " h " + h + " w " + w);
}
//Do something with data for "bad" hotspot
function bad(){
badClicks++;
}
//Do something with data for "skip" hotspot
function skip(){
skipClicks++;
nextImage();
}
//Do something with data for "good" hotspot
function good(){
goodClicks++;
}
//Show the collected data
function displayResults(){
$("#results").append("<br />Bad: " + badClicks
+ " Skip: " + skipClicks
+ " Good: " + goodClicks);
}
</script>
</head>
<body>
<div id="content">
<img id="image" />
<div id="hotspot-wrapper">
<div id="hotspot-a" class="hotspot" onclick="bad();"></div>
<div id="hotspot-b" class="hotspot" onclick="skip();"></div>
<div id="hotspot-c" class="hotspot" onclick="good();"></div>
</div>
</div>
<br />
<div id="results" style="clear:both">
<button onclick="displayResults();" style="text-align: center">Show results</button>
</div>
Any help, tips or advice would be greatly appreciated!
Thanks!
First of all i prefer this way to init images array:
var images = [];
var image = new Image();
image.src = '/some/image/url.jpg';
/* while you doing this image already load in background - so its faster way*/
images.push(image);
You can display this images with jQuery this way:
$('#parend_of_image_div').html(images[iCount]);
And inside your nextImage function use this code:
var img = images[iCount];
$(img).load(function(){
var width = $(this).width()
var height = $(this).height();
/* do other stuff */
});
This is your problem
$("#image").css("width")
However, you havent set #image's width with css. You need to use
$('#image').width()
Also, to be safe, you should only continue with this part of the code AFTER your image has triggered a load event:
//Change image source to new image
$("#image").attr("src", images[iCount]).load(function(){
//Set content wrapper width & height to current image's width & height
$("#content").css("width", $("#image").width());
$("#content").css("height", $("#image").height());
//And then the rest...

Categories

Resources