arrange the div in sequence format using javascript - 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

Related

Can't Inject Variable into Style Margins with 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>

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>

How to make all div height inside a row div similar height to the first child of row

I want to change all div inside row be similar to the height of firstchild of row2 also if the classes are outside of row the div height will be auto and not be change. what's the problem in my code can anyone explain also I dont want to change it from css.
var lgh , lgh_in,mdh,mdh_in,smh,smh_in;
var r = ".row2 >";
var z = ['.lg','.lg-in','.md','.md-in','.sm','.sm-in',];
z.forEach(function (x){
var xx = document.querySelectorAll( r + x );
for ( var j = 0; j < xx.length; j++) {
var ch = document.getElementsByClassName('row2');
for(var i = 0 ; i < ch.length ; i++ ){
var ar = ['lg','lg-in','mdh','md-in','sm','sm-in']; //these are class names , if I put this into my div the div height should be change according to mdh ,lgh ,smh .... etc
for(var k = 0; k < ar.length;k++){
if(ch[i].firstChild.className === ar[k]){
lgh = ch[i].parentNode.clientHeight/ 1.5 ;
lgh_in = ch[i].parentNode.clientHeight - lgh ;
mdh = lgh/ 1.5 ;
mdh_in = ch[i].parentNode.clientHeight - mdh ;
smh = mdh/ 1.5 ;
smh_in = ch[i].parentNode.clientHeight - smh ;
var colors = {};
colors[ar[0]] = lgh;
colors[ar[1]] = lgh_in;
colors[ar[2]] = mdh;
colors[ar[3]] = mdh_in;
colors[ar[4]] = smh;
colors[ar[5]] = smh_in;
ch[i].firstChild.style.height = mdh + "px"; //if I remove the px then output is different also
document.getElementById('demo').innerHTML = mdh ; // only for output checking
if (ch[i].parentNode.tagName === "BODY") {
ch[i].style.height = "auto"; // if the div2 parent is body then height will be auto.
}
}
}
}
}
});
so I able to change the first child div but I cant change all div inside of the row2 which is my problem,
HTML
<div class="main"><div class="row2"><div class="lg">xfghjgjgx</div><div class="lg-in">xfgvcbvx</div></div>
<div class="row2"><div class="lg-in">xfghjgjgx</div><div class="lg">xfgvcbvx</div></div>
Jquery is easier.. Id do something like this?
// For each .box element
$('.box').each(function() {
// Set up the variables
var $this = $(this),
w = $this.find('img').width(), // Width of the image inside .box
h = $this.find('img').height(); // Height of the image inside .box
$this.width(w).height(h); // Set width and height of .box to match image
});
Variant with same height of all blocks ( https://jsfiddle.net/br3t/fmovbtp1/ )
var classes = ["lg", "lg-in", "md"];
var requiredHeight = window.getComputedStyle(document.querySelector(".row2 .lg")).height;
classes.forEach(function(cls) {
document.querySelectorAll("." + cls).forEach(function(item) {
item.style.height = requiredHeight;
});
});

Add html code to a dynamically generated div

I have a js question that annoys me for the last couple of days.
i have a parallax template, where the parallax elements are generated automatically from js file.So i can add css style like transitions etc., but i would like to add some links on top of the divs, or some kind of on clik events.
What i think i have to look so far is in this fille (where the id of the divs are created):
enter //Parallax Element 2
var item = {};
item.name = "#tree21";
item.stackOrder = 1;
item.content = "image";
item.image = "images/parallax/bg2.png";
item.sizes = {w:"350",h:"350"};
item.screenPos = ["40%","-100%","300%","-115%"];
item.visibility = ["true","true","true","true"];
item.parallaxScene = true;
item.bPos = 200;
item.mouseSpeed = 15;
items.push(item);
and here (where i think the divs are generated
createScenes: function () {
//Resize Parallax Elements if responsive
if (responsive) {
var screenProp = this.maxWidth / 1920;
} else {
var screenProp = 1;
}
for (var i = 0; i < items.length; i++) {
if (jQuery(items[i].name).length == 0) {
jQuery("#parallax-container").append("<div id='" + items[i].name.substring(1, (items[i].name.length)) + "' class='parallaxItem'></div>");
}
Thank you!
Store a reference to your new div:
var div = jQuery("<div id='"
+ items[i].name.substring(1, (items[i].name.length))
+ "' class='parallaxItem'></div>")
.appendTo(jQuery("#parallax-container"));
jQuery(div).append('...');

Slide dynamically added content with jQuery

I'm trying to create a simple content slider that could handle dynamically added content to the slider. None of the "lightweight" plugins I found provided such functionality or, if it did, it didn't work correctly.
var $left = $('.left'),
$right = $('.right'),
$months = $('.sub ul');
$left.click(function(){
for(i = 0; i < 3; i++){
$months.find('li').first().before($.parseHTML('<li>xxx</li>'));
}
pos = $months.position();
$months.css('left', pos.left + 90);
});
$right.click(function(){
for(i = 0; i < 3; i++){
$months.find('li').last().after($.parseHTML('<li>xxx</li>'));
}
pos = $months.position();
$months.css('left', pos.left - 90);
});
This is the code I've got so far and here's a fiddle with an example - http://jsfiddle.net/kkr4zg0r/2/. It kind of works, but the problem is that since new content is added the navigation goes off (you can see what I mean by clicking left-right a couple of times).
I understand what's the problem for this - the newly added items "shift" the content and I need to do better calculations than substracting/adding 90px to the left position of the element but I can't figure out how to get the correct index of the elements and basically get this sliding by exactly (and correctly) by 3(or 6) elements at the time.
Currently the code is adding extra elements whenever a navigation button is pressed, if I could get the index of the currently visible first/last element, I could probably tell whether I need to add more elements and only add them then.
This is a basic illustration of what I'm trying to achieve
edit
I've changed the jsfiddle to the correct one.
The whole idea is to check when adding elements is necessary and when shift is enough:
Fiddle
$(document).ready(function()
{
var $main = $('.main'),
$left = $('.left'),
$right = $('.right'),
$months = $('.sub ul');
var addCount = 3;
var liWidth = 30;
var shiftX = addCount * liWidth;
$left.click(function()
{
var currentLeft = parseInt($months.css('left'));
var totalLength = $months.find('li').length * liWidth;
if (-currentLeft + $main.width() >= totalLength)
{
for (var i = 0; i < addCount; i++)
{
$months.find('li:last').after('<li>xxx</li>');
}
}
$months.css('left', currentLeft -= shiftX);
});
$right.click(function()
{
var currentLeft = parseInt($months.css('left'));
if (currentLeft < 0)
{
$months.css('left', currentLeft += shiftX);
}
else
{
for (var i = 0; i < addCount; i++)
{
$months.find('li:first').before('<li>xxx</li>');
}
}
});
});

Categories