Can't Inject Variable into Style Margins with Javascript - javascript

Fairly easy solution to this problem, I'm pretty sure, but I'm still currently unable to find where the problem may be (probably some syntax).
I'm trying to create a simple JS exercise to move an object's position to a random place after each hover/mouseover. (DOM manipulations fundamentals).
Here is the code:
let arr = [".top", ".left"];
let logTest = []
document.querySelectorAll('div').forEach(occurence => {
occurence.addEventListener('mouseover', (e) => {
for (let i = 0; i < 2; i++) {
var num = Math.floor((Math.random() * 100) + 1);
e.target.style[arr[i]] = num + "px";
logTest[i] = num + "px";
}
console.log(logTest[0] + ", " + logTest[1]);
});
});
Since the numbers are being generated and printed correctly to the console, I'm fairly sure that the problem has to be in line 9, where e.target.style[.left and .top] is not being able to be assigned to the random numbers.

let arr = [".top", ".left"];
Don't use '.' dots for specifying the style. Directly use the style property name. Use this:
let arr = ["top", "left"];
And make sure to set position as relative, absolute or fixed for the div elements.
Here's a working example made using your script:
<style>
.t {
height: 50px;
width: 50px;
background: green;
margin: 10px;
position: relative;
}
</style>
<h1>Hello</h1>
<div class="t">e</div>
<div class="t">f</div>
<script>
let arr = ["top", "left"];
let logTest = []
document.querySelectorAll('div').forEach(occurence => {
occurence.addEventListener('mouseover', (e) => {
for (let i = 0; i < 2; i++) {
var num = Math.floor((Math.random() * 100) + 1);
e.target.style[arr[i]] = num;
logTest[i] = num;
}
console.log(logTest[0] + ", " + logTest[1]);
});
});
</script>

Related

Toggle style properties with JavaScript by commenting-out CSS attributes

I want to send a list of properties to a function that will temporarily disable (via comments) those properties. The purpose is similar to what is accomplished by Chrome Dev Tools when inspecting the style of an element, except that the user will not check/uncheck boxes, instead, the action will be performed by JavaScript.
function disableProperties(el, properties) {
var property; // property value pair
var cssStr = el.style.cssText.replace(/; /g, ";");
for (let i = 0; i < properties.length; i++) {
property = properties[i] + ": " + eval("el.style." + properties[i]) + ";";
cssStr = cssStr.replace(property, "/* " + property + " */");
}
el.setAttribute("style", cssStr);
}
function restoreProperties(el, properties) {
var outHtml = el.outerHTML;
var key = 'style="';
var idx1 = outHtml.indexOf(key) + key.length;
var idx2 = outHtml.indexOf('"', idx1);
var style = outHtml.substring(idx1, idx2);
for (let i = 0; i < properties.length; i++) {
str = "/* " + properties[i];
let a = style.indexOf(str);
let b = style.indexOf(" */", a + a.length) + 3;
let comment = style.substring(a, b);
let property = (comment).replace("/*", "").replace("*/", "");
style = style.replace(comment, property);
}
el.style.cssText = style;
}
When elements are created, their style is embedded in the HTML instead of external CSS files. It is important that the properties are only temporarily disabled; their earlier values must be preserved.
UPDATE:
I thought my comment code was not working because I was trying to retrieve the comment by asking for el.style.cssText; however, the comment was only available through outerHTML.
The code below is functional, but I'm sure that could be cleaned up. If you have suggestions on how I can improve this code, please advise. Here is a fiddle to demonstrate one example of how I am using the code.
Expanding on Volts deleted answer, use data attributes to store the initial state of your element. You can then that information to reset the values. One catch is that the style property is read only, so if we want to reset all style properties, we have to loop all the properties.
This is much cleaner than hacking comments in and out. This works with styles set inline and with classes.
const disableProperties = (el, properties) => {
//store the style so we can restore it
el.dataset.styles = JSON.stringify(el.style);
console.log(JSON.parse(el.dataset.styles));
properties.forEach(property => {
el.style[property] = "unset";
})
}
const enableProperties = (el, properties) => {
//Get our saved initial state
let styles = JSON.parse(el.dataset.styles);
console.log(styles);
properties.forEach(property => {
el.style[property] = styles[property];
})
}
const restoreAll = (el) => {
let styles = JSON.parse(el.dataset.styles);
console.log(styles);
/*You might think the following line should work, but the styles property is read only*/
/*el.style = styles;*/
/*So loop our properties instead*/
for(prop in styles){
if(styles.hasOwnProperty(prop)){
el.style[prop] = styles[prop];
}
}
}
document.querySelector('.child').addEventListener("click", function() {
disableProperties(this.parentNode, ["top", "left"])
})
let enableButtons = document.querySelectorAll(".enable");
for (var i = 0; i < enableButtons.length; i++) {
enableButtons[i].addEventListener("click", function(event) {
let property = this.dataset.restore;
let target = document.querySelector(this.dataset.target);
enableProperties(target, property.split(","));
});
}
document.getElementById("restoreAll").addEventListener("click", function() {
restoreAll(document.querySelector(".parent"));
});
.parent {
/*top: 50px;*/
left: 50px;
position: absolute;
}
.child {
background: red;
width: 50px;
height: 50px;
}
.container {position:relative; height:200px;}
Click the square before restoring
<div class="container">
<div class="parent" style="top:50px;">
<div class="child">
</div>
</div>
</div>
<button id="restoreLeft" class="enable" data-restore="left" data-target=".parent">Restore Left</button>
<button id="restoreTop" class="enable" data-restore="top" data-target=".parent">Restore top</button>
<button id="restoreAll">RestoreAll</button>

Determining how many table rows are visible on the screen before scroll-bar shows up [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Background: I am working on a dashboard, which shows a header and a table underneath. The table can have many rows (over 100).
Problem: large number of rows triggers a vertical scrollbar to show up, which hides the rest of the rows.
Possible solution: I would like to rotate, what table rows are showed on every screen the dashboard is on. I would like to avoid to set a fixed number of rows that are visible on screen and instead, determine how many rows can be put on the screen before the scroll bar shows up. This means that, first, I would like to determine how many rows are visible on the screen before the scrollbar shows up, and then create a carousel animation, where the next X rows are showed until all the rows are showed and the animation resets.
Technologies used: React JS, Bootstrap table
For the carousel part, I found Bootstrap Carousel to work fine, but the problem is figuring out, how many rows are visible on the screen. How do I determine, how many rows I can display on the screen before the scroll-bar shows up? Thank you very much!
One possible solution would be:
Create an element in the DOM which would be 100% height (any other possible height will work too). For example:
<div id="row-wrapper" style="height: 100%"></div>
Get the height of the element.
var availableHeight = document.getElementById('row-wrapper').clientHeight;
Knowing how much height your single row occupies just divide availableHeight and you will know how many rows to render. In case your row height is 30:
var numberOfRows = Math.floor(availableHeight / 30);
I know you tagged ReactJS, but a good basis is to always keep your DOM as small as possible. My tactic would be to keep the data in JavaScript and only introduce to the DOM what is absolutely needed.
Below is a simple example showing 10 rows with an offset:
var dummyData = [];
(function populateData() {
var names = ["Greg", "Jeff", "Bob", "Bruce", "Clark", "Diana"];
while (dummyData.length < 100000) {
dummyData.push({
name: names[Math.floor(Math.random() * names.length)],
age: Math.floor(Math.random() * 100)
});
}
})();
function displayData(data, offset, limit) {
if (offset === void 0) {
offset = 0;
}
if (limit === void 0) {
limit = data.length;
}
var tbody = document.body.appendChild(document.createElement("tbody"));
for (var i = offset; i < (limit + offset); i++) {
if (i >= data.length) {
break;
}
var person = data[i];
var tr = tbody.appendChild(document.createElement("tr"));
tr.innerHTML = "<td>" + i + "</td><td>" + person.name + "</td><td>" + person.age + "</td>";
}
return tbody;
}
var pagesize = 10;
var offset = 0;
var offsetInput = document.body.appendChild(document.createElement("input"));
offsetInput.type = "number";
offsetInput.min = "0";
offsetInput.value = "0";
var table = document.body.appendChild(document.createElement("table"));
table.style.width = "100%";
table.innerHTML = "<thead><tr><th>Index</th><th>Name</th><th>Age</th></tr></thead>";
var tbody = table.appendChild(displayData(dummyData, offset, pagesize));
function update() {
if (offsetInput.validity.valid) {
offset = parseInt(offsetInput.value, 10);
table.removeChild(tbody);
tbody = displayData(dummyData, offset, pagesize);
table.appendChild(tbody);
}
}
offsetInput.addEventListener("change", update);
offsetInput.addEventListener("keyup", update);
From here it would be a matter of some CSS tricking and reading the scrollbar to get an offset.
var dummyData = [];
(function populateData() {
var names = ["Greg", "Jeff", "Bob", "Bruce", "Clark", "Diana"];
while (dummyData.length < 100) {
dummyData.push({
name: names[Math.floor(Math.random() * names.length)],
age: Math.floor(Math.random() * 100)
});
}
})();
function displayData(data, offset, limit) {
if (offset === void 0) {
offset = 0;
}
if (limit === void 0) {
limit = data.length;
}
var tbody = document.body.appendChild(document.createElement("tbody"));
for (var i = offset; i < (limit + offset); i++) {
if (i >= data.length) {
break;
}
var person = data[i];
var tr = tbody.appendChild(document.createElement("tr"));
tr.innerHTML = "<td>" + i + "</td><td>" + person.name + "</td><td>" + person.age + "</td>";
}
return tbody;
}
var pagesize = 10;
var offset = 0;
var offsetInput = document.body.appendChild(document.createElement("input"));
offsetInput.type = "number";
offsetInput.min = "0";
offsetInput.max = "" + (dummyData.length - pagesize);
offsetInput.value = "0";
var outerContainer = document.body.appendChild(document.createElement("div"));
outerContainer.style.maxHeight = "400px";
outerContainer.style.width = "450px";
outerContainer.style.overflowY = "scroll";
var innerContainer = outerContainer.appendChild(document.createElement("div"));
innerContainer.style.height = dummyData.length * 20 + 200 + "px";
var table = innerContainer.appendChild(document.createElement("table"));
table.style.position = "absolute";
table.style.width = "400px";
table.innerHTML = "<thead><tr><th>Index</th><th>Name</th><th>Age</th></tr></thead>";
var tbody = table.appendChild(displayData(dummyData, offset, pagesize));
var handle;
function update() {
table.removeChild(tbody);
tbody = displayData(dummyData, offset, pagesize);
table.appendChild(tbody);
clearTimeout(handle);
handle = setTimeout(function() {
offsetInput.value = offset.toString();
outerContainer.scrollTop = offset * 20;
}, 100);
}
function updateInput() {
if (offsetInput.validity.valid) {
offset = parseInt(offsetInput.value, 10);
}
update();
}
function updateScroll() {
offset = Math.floor(outerContainer.scrollTop / 20);
update();
}
outerContainer.addEventListener("scroll", updateScroll);
offsetInput.addEventListener("change", updateInput);
offsetInput.addEventListener("keyup", updateInput);
This is an example how you can fill a div until its full. Made a jQuery answer too if someone is interested in that.
I made 2 div's. One with a set height(100% in the example but can be static height too) and inside a growable div that grows with the content.
First it will fill the growable div as long it is smaller then the content div.
The last added element could be bigger then the remaining space. If that happens it removes the last element.
This also works with content with dynamic heights.
Note: When using while loops it's always good to have a backup plan to avoid infinite loops. Therefore I added a max records variable.
Javascript:
window.onload = function() {
document.getElementById('fill').onclick = function() {
var content = document.getElementById('content');
var growableWrapper = document.getElementById('growableWrapper');
var maxRecords = 50;
while ((content.childNodes.length === 0 || parseInt(window.getComputedStyle(growableWrapper).height) < parseInt(window.getComputedStyle(content).height)) && growableWrapper.childNodes.length < maxRecords) {
var newElement = document.createElement("p");
var newText = document.createTextNode("Test");
newElement.appendChild(newText);
growableWrapper.appendChild(newElement);
}
if (window.getComputedStyle(growableWrapper).height > window.getComputedStyle(content).height && growableWrapper.childNodes.length > 1) {
growableWrapper.removeChild(growableWrapper.childNodes[growableWrapper.childNodes.length - 1]);
}
}
}
html,
body,
#content {
margin: 0;
padding: 0;
height: 100%;
}
#fill,
#content {
width: 40%;
float: left;
}
#content {
background-color: gray;
overflow: hidden;
}
#growableWrapper {
background-color: lightgray;
overflow: auto;
}
<div>
<button id="fill">Fill</button>
</div>
<div id="content">
<div id="growableWrapper">
</div>
</div>
jQuery:
$(document).ready(function() {
$('#fill').on('click', function() {
var content = $('#content');
var growableWrapper = $('#growableWrapper');
var maxRecords = 50;
while ((content.children().length === 0 || growableWrapper.height() < content.height()) && growableWrapper.children().length < maxRecords) {
growableWrapper.append('<p>test</p>');
}
if(growableWrapper.height() > content.height() && growableWrapper.children().length > 1) {
growableWrapper.children().last().remove();
}
});
});
html,
body,
#content {
margin: 0;
padding: 0;
height: 100%;
}
#fill, #content {
width: 40%;
float: left;
}
#content {
background-color: gray;
overflow: hidden;
}
#growableWrapper {
background-color: lightgray;
overflow: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<button id="fill">Fill</button>
</div>
<div id="content">
<div id="growableWrapper">
</div>
</div>

Select random number from string of 1's and 0's and change color

I have a string of random 1's and 0's displayed via jQuery. I would now like to select a random number and change it's color. Is it better to work with an array, or a $(div).text() string? I can grab a number from either, but how do I insert it back into the div?
var numbArray = [];
for(i=0; i<10; i++)
{
var randomNumbers = Math.round(Math.random());
$('#numbs').prepend(randomNumbers);
numbArray[i] = randomNumbers;
}
<div id="numbs">0000110111 </div>
The div above is the result of the code, but how do I select a random item, change its color, and display in the original output?
Thanks,
You can locate the number at a certain index, wrap it with the desired color and rebuild the string and set it back to the div using html() and use Math.floor(Math.random() * 10) to generate the random number from zero to the length of the characters you have.
var index = 3;
var originalElementValue;
function colorStringValue(strIndex)
{
strIndex = parseInt(strIndex);
var character = originalElementValue.charAt(strIndex);
$("#numbs").html(originalElementValue.substr(0, strIndex) + "<span style='color:red'>" + character + "</span>" + originalElementValue.substr(strIndex+1));
}
$(document).ready(function(){
originalElementValue = $("#numbs").text();
colorStringValue(index);
$("#strIndex").click(function(){
var rand = Math.floor(Math.random() * 10) + 0 ;
$("#rand").html(rand);
colorStringValue(rand);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="strIndex" > Generate Random Number </button>
<br />
Random Number : <span id="rand"></span>
<br />
<div id="numbs">0000110111</div>
You need to pick a random index from the number string and append some element around that particular number to give it some style.
var number = '0000110111';
var index = Math.floor(Math.random() * number.length);
for(var i = 0; i < number.length; i++) {
var n = number.charAt(i);
if(i == index) {
$('#numbs').append($('<span/>').css('color', 'red').text(n));
} else {
$('#numbs').append(n);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="numbs"></div>
var numbArray = [];
for(i = 0; i< 10; i++) {
var randomNumbers = Math.round(Math.random());
numbArray[i] = randomNumbers;
$('#numbs').prepend(number);
}
var randomNumberSelection = numbArray[Math.floor((Math.random() * (numbArray.length-1)) + 1)];
$('#numbs').html("");
var number;
for(number in numbArray) {
if(number == randomNumberSelection) {
var colorColorCodedNumber = ""+number;
colorColorCodedNumber = colorColorCodedNumber.fontcolor("blue");//blue!
$('#numbs').prepend(colorColorCodedNumber);
} else {
$('#numbs').prepend(number);
}
}
I believe you're looking for something along the lines of this, or at least this is what I took from what you were asking.
In this example be aware you'll see we clear the element then simply reiterate over the array you stored earlier. That is how you 'update' it.
If I understand the question right you want to set a color for a specific position in the div. This means you have to create a span (or another html-element) inside the div at at a random position with a specific color. I havent tested this code below but I guess you could something like this: (in this example red color for the random item)
var randomIndex= Math.floor(Math.random() * 9); //Random number between 0 and 9.
var currentContent = $("#numbs").html();
var randomItem= currentContent.charAt(randomIndex);
newContent = '';
for(i=0; i<10; i++) {
if (i == randomIndex) {
newContent = newContent +
'<span style="background:red;">' + randomItem + '</span>';
}
else {
newContent = newContent + currentContent.charAt(i);
}
}
$("#numbs").html( newContent );
Is this what you are looking for? I just gave it a try. :)
var numbArray = [];
var sample = "<span style='color:#%COLOR%'>%NUM%</span>";
for(i=0; i<10; i++)
{
var randomNumbers = Math.round(Math.random());
var html = sample.replace('%NUM%', randomNumbers);
var randomColor = Math.round((Math.random()* 100000000 )%16777215).toString(16);
html = html.replace('%COLOR%', randomColor);
$('#numbs').prepend(html );
numbArray[i] = randomNumbers;
}
I assumed that you want random colors too.
Good answers by all; thanks! I didn't think of appending the DOM and redisplaying. I went with assigning each number an id and then using css without appending. I was looking for numbers that would turn a color and when all the numbers were that color the script would stop. I don't know which method would perform the best but this way is okay for my limited numbers.
var whiteNumbs =
[0,1,1,0,1,1,0,1,0,1,1,0,0,0,0,1,0,1,1,1,0,0,1,0,0,1,1,1,0,0,1,0]
for(var i=0; i<whiteNumbs.length; i++)
{
$("#numbs").append('<span class="white" id="num_' + i + '">' +
whiteNumbs[i] + '</span>');
}
function MakeRed()
{
var randomNumber = Math.floor(Math.random() * whiteNumbs.length-1);
var changeCSS = "#num_" + randomNumber;
$(changeCSS).removeClass('white');
$(changeCSS).addClass("red");
if ($("#numbs span").hasClass("white") )
{
setTimeout(MakeRed,1000);
}
else
{
return false;
}
};
MakeRed();

Create onmouseover/onmouseout functions dynamically with javascript?

So here is an example of the function I need to replicate:
document.getElementById('img1').onmouseover = function() {
document.getElementById('img1').style.width = expandTo + '%';
expandCompensate(1);
}
document.getElementById('img1').onmouseout = function() {
expandReset();
}
The situation is that I have a for loop creating some div elements, and the number of them is dynamic. As of right now, I have it creating 4 div elements, so I created 4 iterations of the above functions for img1, img2, img3 and img4. But what I would like to do is to have the onmouseover and onmouseout functions created dynamically based on how many div elements I've decided to create (based on a variable).
Is there any way to do this? Here is all the code for context (it's not much), there are comments in the JS with explanations for everything. The part I'm trying to automate is at the bottom:
https://jsfiddle.net/4w0714su/3/
And here is the working example for context of what I'm trying to achieve:
http://www.ericsartor.ca/imgwide
FYI: The image is I picked were random, I just needed high res images. Just doing this for practice! Thanks to anyone that can help me figure this out!
I can't understand your code very well, but I'll answer particularly what you're asking.
You can achieve what you want by doing a loop:
for (var i = 0; i < 4; i++) {
document.getElementById('img' + i).onmouseover = function() {
this.style.width = expandTo + '%';
expandCompensate(Number(this.id.replace('img', '')));
};
document.getElementById('img' + i).onmouseout = function() {
expandReset();
}
}
Note: you can't use the i variable inside the event handlers' functions, because it will always be 4, since it will finish the loop, and will never be changed again.
Another way of doing that is by using an IIFE (Immediately-invoked function expression), e.g:
for (var i = 0; i < 4; i++) {
(function(n) {
document.getElementById('img' + n).onmouseover = function() {
this.style.width = expandTo + '%';
expandCompensate(n);
};
document.getElementById('img' + n).onmouseout = function() {
expandReset();
}
})(i);
}
Doing that, you're passing to a function the current i value, so in that scope, the value of n will be a different one for each execution, e.g 0, 1, 2 and 3.
An immediately-invoked function expression (or IIFE, pronounced
"iffy") is a JavaScript design pattern which produces a lexical scope
using JavaScript's function scoping.
This could be achieved by iterating all those DOM elements and binding events in a loop.
As we bind events in loop, and event callback is being executed later when loop would be iterated completely, we need to maintaing the value of current iteration using CLOSURE.
Try this snippet:
var pageHeight = document.getElementById('findBottom').getBoundingClientRect().bottom,
numOfPics = 4; //the number of div elements to create
//creates the div elements within a container div in the HTML document
for (var i = 1; i <= numOfPics; i++) {
document.getElementById('imgContain').innerHTML += '<div id="img' + i + '" class="imgPane"></div>';
}
//used to resize all divs if the window changes size
window.onresize = function() {
pageHeight = document.getElementById('findBottom').getBoundingClientRect().bottom;
for (var i = 1; i <= imgClasses.length; i++) {
document.getElementById('img' + i).style.height = pageHeight + 'px';
}
for (var i = 1; i <= imgClasses.length; i++) {
document.getElementById('img' + i).style.width = 100 / imgClasses.length + '%';
}
};
//sets the height of each div to be the mximum height of the page (without scrolling)
for (var i = 1; i <= numOfPics; i++) {
document.getElementById('img' + i).style.height = pageHeight + 'px';
}
//makes all the divs equal percentage widths
for (var i = 1; i <= numOfPics; i++) {
document.getElementById('img' + i).style.width = 100 / numOfPics + '%';
}
//the percentage of the page the hovered image will expand to
var expandTo = 40;
//function for when an image is hovered over
function expandCompensate(whichImg) {
for (var i = 1; i <= numOfPics; i++) {
if (i != whichImg)
document.getElementById('img' + i).style.width = (100 - expandTo) / (numOfPics - 1) + '%';
}
}
//function for when the hovered image is left to reset the widths
function expandReset() {
for (var i = 1; i <= numOfPics; i++) {
document.getElementById('img' + i).style.width = 100 / numOfPics + '%';
}
}
(function bindEvents() {
for (var i = 1; i <= numOfPics; i++) {
document.getElementById('img' + i).onmouseover = (function(i) {
return function() {
document.getElementById('img' + i).style.width = expandTo + '%';
expandCompensate(i);
}
})(i);
document.getElementById('img' + i).onmouseout = function() {
expandReset();
};
}
})();
body,
p,
div {
margin: 0;
padding: 0;
}
body {} #findBottom {
position: absolute;
bottom: 0;
}
.imgPane {
float: left;
background-position: center;
transition: width 0.25s;
}
#img1 {
background-image: url('http://www.ericsartor.ca/imgwide/img//1.jpg');
}
#img2 {
background-image: url('http://www.ericsartor.ca/imgwide/img//2.jpg');
}
#img3 {
background-image: url('http://www.ericsartor.ca/imgwide/img//3.jpg');
}
#img4 {
background-image: url('http://www.ericsartor.ca/imgwide/img//4.jpg');
}
<div id="imgContain"></div>
<!-- ABSOLUTE ELEMENTS -->
<div id="findBottom"></div>
<!-- ABSOLUTE ELEMENTS -->

arrange the div in sequence format using javascript

I am working on scenario where when I enter number in the textbox i need generate dynamically div's. Actually I am struggling not aligned properly with the current div. Then I need to generate ID's for the div's. For this also code is available but the code not considered the default div as preview1 then it has to go on like preview2, preview3 so on. The div has to arrange sequence like first it has to show preview1......
var inputElement = document.getElementById("inputAdd_page");
var totalCount = 0;
inputElement.addEventListener('blur', function () {
var count = this.value;
// Gaurd condition
// Only if it is a number
if (count && !isNaN(count)) {
fragment = document.createDocumentFragment();
for (var j = 0; j < count; ++j) {
spancount = document.createElement('span');
prevPage = document.createElement('div');
navbutton = document.createElement('button');
preview_PageSize = document.getElementById('page');
navbutton.className = "div_navig";
navbutton.setAttribute('id', ['pag_navg' + totalCount]);
navbutton.innerHTML = [1 + totalCount];
spancount.className = "spanCount";
spancount.innerHTML = [1 + totalCount];
prevPage.className = "preview_windowSize";
prevPage.setAttribute('id', ['page' + totalCount]);
prevPage.appendChild(spancount);
prevPage.style.position = "absolute";
preview_PageSize.appendChild(prevPage);
//fragment.appendChild(prevPage);
fragment.appendChild(navbutton);
totalCount++;
}
inputElement.value = "";
document.body.appendChild(fragment);
}
});
Here is the fiddle Link
Thanks in advance.
Kindly help me.
if I get you right, change the javascript as follows:
//prevPage.style.position="absolute";
//preview_PageSize.appendChild(prevPage);
prevPage.style.width="100%";
preview_PageSize.parentNode.insertBefore(prevPage, preview_PageSize);
to improve positioning, you could apply a diffrent class to the child elements, like so:
prevPage.className = "preview_windowSize_element";
and use CSS:
.preview_windowSize_element {
position: absolute;
left: 31px;
top: 0px;
width: 100%;
height: 100%;
}
to start with page ID 1 you could modify your script:
prevPage.setAttribute('id', ['page' + (totalCount + 1)]);
Do you search something like this jsFiddle?.
I just add a left position in each div, because you set them to position:absolute.
So I added this line:
prevPage.style.left= (26 * totalCount) + "px";
I just put 26 like this, it will be the width of the button

Categories