JS: split and replace 1 ul into 2 equal ul's - javascript

I have a variable in which i search for ul's. I want every ul to split into 2 equal ul's and replace the original ul with these 2 new ul's.
I can't do this with CSS, because i want the li's to display from top to bottom every column, instead of from left to right.
I have the following code, but I am stuck right now...
<script type="text/javascript">
var wid_tekst1 = "<?php echo $wid_tekst1; ?>";
$(wid_tekst1).filter('ul').each(function() {
//Create array of all posts in lists
var postsArr = new Array();
$postsList = $(this);
$(this).find('li').each(function(){
postsArr.push($(this).html());
})
//Split the array at this point. The original array is altered.
var firstList = postsArr.splice(0, Math.round(postsArr.length / 2)),
secondList = postsArr,
ListHTML = '';
function createHTML(list){
ListHTML = '';
for (var i = 0; i < list.length; i++) {
ListHTML += '<li>' + list[i] + '</li>'
};
}
//$(firstList).before('<ul>');
//$(firstList).after('</ul>');
//$(secondList).before('<ul>');
//$(secondList).after('</ul>');
alert(firstList);
alert(secondList);
})
</script>
Thanks for your help...
UPDATE:
I now have the following:
<script type="text/javascript">
$( document ).ready(function() {
var wid_tekst1 = $('.content');
$(wid_tekst1).filter('ul').each(function() {
var $li = $(this).children(),
$newUl = $('<ul>').insertAfter(this),
middle = Math.ceil($li.length / 2) - 1;
$li.filter(':gt(' + middle + ')').appendTo($newUl);
//alert($newUl);
});
});
</script>
It doesn't split the ul's into 2. The only way I got it working was by setting
var wid_tekst1 = "*";
But if I set variable wid_tekst1 to all, it replaces all ul's in the webpage. I only want to replace the ul's within the .content-class
Thank you

Your code can be optimized:
$(wid_tekst1).filter('ul').each(function() {
var $li = $(this).children(),
$newUl = $('<ul>').insertAfter(this),
middle = Math.ceil($li.length / 2) - 1;
$li.filter(':gt(' + middle + ')').appendTo($newUl);
});
Demo: http://jsfiddle.net/R3VYZ/
Messing with innerHTML (when you construct lists using strings) is not ideal, since you will lose all event original handlers if there were something bound.

Related

Create element until condition is true

I want to create elements inside another element until condition is true.
I have tried this code but it's not working.
// calculate span size and it's parent
var homeHeight = $(".home").height();
var homeWidth = $(".home").width();
var homeSize = (homeHeight + homeWidth) * 2;
var spanHeight = $(".back-animation span").height();
var spanWidth = $(".back-animation span").width();
var spanSize = (spanHeight + spanWidth) * 2;
// create span elements to fill it's parent.
var createSpan = function() {
var span = document.createElement("span");
while (spanSize <= homeSize) {
$(".animation-hide-overflow").append(span);
spanSize = spanSize + spanSize;
}
};
createSpan();
Note: It's combined with JQuery and I recieve no errors in console.
Note 2: I tried for loop like the bottom but it's not working either.
for (spanSize; spanSize <= homeSize; spanSize = spanSize + spanSize) {
$(".animation-hide-overflow").append(span);
}
EDIT:
Thanks for mentioning, I forgot to call createSpan function! now it's working but it create span just once. Any solutions?
jsfiddle for better demonstration:
http://jsfiddle.net/pooria_h/vqmgmyj0/1/
(It should keep creating span elements until it fills up parent element.)
The problem was this section
// create span elements to fill it's parent.
var createSpan = function() {
var span = document.createElement("span");
while (spanSize <= homeSize) {
$(".animation-hide-overflow").append(span);
spanSize = spanSize + spanSize;
}
}
If you pay more attention you can see I've created span variable outside of the loop, So this is what happens: Loop works correctly and it increases spanSize variable until it equals to homeSize variable which is bigger in the start point but the big problem is there isn't a element creation! span element is created before the loop.
So this is the correct way:
// create span elements to fill it's parent.
var createSpan = function() {
while (spanSize <= homeSize) {
var span = document.createElement("span");
$(".animation-hide-overflow").append(span);
spanSize = spanSize + spanSize;
}
}

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('...');

Why isn't JavaScript for loop incrementing?

I'm trying to replace the <li> with 1. 2. 3. respectively. I managed to change the <li> to a number, but that number is 0. The loop doesn't want to work. To be honest, this method may be impossible.
Take a look at the Fiddle if you'd like.
This is my function(){...} :
function doIt(){
var input = document.getElementById("input");
var li = /<li>/; // match opening li
var liB = /<\/li>/; // match closing li
var numberOfItems = input.value.match(li).length; // number of lis that occur
for(var i = 0; i < numberOfItems; i++) {
insertNumber(i); // execute insertNumber function w/ parameter of incremented i
}
function insertNumber(number){
input.value = input.value.replace(li, number + "." + " ").replace(liB, "");
}
}
I understand the insertNumber(){...} function is not necessary.
Here's an alternative method, turning your HTML textarea contents into DOM elements that jQuery can manipulate and managing them that way:
function doIt() {
var $domElements = $.parseHTML( $('#input').val().trim() ),
output = [],
i = 1;
$.each($domElements, function(index, element) {
if($(this).text().trim() != '') {
output.push( i + '. ' + $(this).text().trim() );
i++;
}
});
$('#input').val(output.join('\n'));
}

jQuery loop through table to display values

I'm at a loss here.
I created a quick script that will add a new row to a table and also has the capability to delete a row.
jsFiddle -->http://jsfiddle.net/wLpJr/10/
What I want to achieve is this:
Display each value of each row (in the div with id='thedata')
I originally started off with adding a number at the end of each id, starting at '1', and incrementing each time the user adds a row.
//This is random code
var rowcount = parseInt($('#rowcount').val());
var newcount = rowcount + (1*1);
var x = $('#radioinput' + newcount).val('a value');
$('#rowcount').val(newcount);
The problem is that lets say you add 5 rows. Now delete row 3. When you loop through the table of data you will get an error because row "3" does not exist. You have rows 1, 2, 4, 5, 6. Specifically - the input with id = 'radioinput3' will not be present.
I then decided to do this:
$('#maintable > tbody > tr').each(function() {
radiovalue[i] = $("input[type='hidden']", this).map(function() {
var vid = 'radio' + i;
var myval = this.value;
var radioinput = document.createElement("input");
radioinput.type = "hidden";
radioinput.value = myval; // set the CSS class
radioinput.id = vid;
$('#maintable').append(radioinput);
}).get()
text1value[i] = $('td > input', this).map(function() {
var vid = 'text1pos' + i;
var myval = this.value;
var text1input = document.createElement('input');
text1input.type='hidden';
text1input.value = myval;
text1input.id = vid;
$('#maintable').append(text1input);
}).get()
text2value[i] = $('td > input', this).map(function() {
var vid = 'text2pos' + i;
var myval = this.value;
var text2input = document.createElement('input');
text2input.type='hidden';
text2input.value = myval;
text2input.id = vid;
$('#maintable').append(text2input);
}).get();
});
The problem here is that I'm getting 'undefined' values.
You are looping through a counter, which you increment everytime you add a new row, but do not take into account that a row can be deleted at any time. Instead, just use the each function to loop over the elements remaining in the DOM.
Add thead and tbody tags to your table, it will make your life easier.
I'm not sure why you have those hidden div to hold the input[type=radio] values, you don;t need them, access the values directly.
$('#showdata').click(function() {
$("#maintable tbody tr").each(function(i, v) {
var myp = "<p>Radio value is = " + $(this).find('input[type=radio]:checked').val()
+ "\nText1 value is = " + $(this).find('input[id$=text1]').val()
+ "\nText2 value is = " + $(this).find('input[id$=text2]').val() + "</p>";
$('#thedata').append(myp);
});
});
jsFiddle Demo
You could add a CSS class to the input text fields to make it easier to get, but i just used the jQuery ends with selector.
Also, you delete selector if far too high up the DOM tree on (document), instead restrict it as near as you can, in this case the #maintable.

Change innerhtml of all h2 elements within div

This is probably a stupid mistake, but i can't seem to get this to work.
I'm trying to change the innerhtml of all the H2 elements withing the div whose id=variable id.
var numberOfQuestions = $('.question').length;
var id = "question"+(numberOfQuestions);
clone.id=id;
document.documentElement.getElementById(id).getElementsByTagName( "h2" ).innerhtml= "Question"+(numberOfQuestions);
I think I'm doing something wrong here: document.documentElement.getElementById(id).getElementsByTagName( "h2" ).innerhtml= "Question"+(numberOfQuestions);
The nrtire script:
<script type="text/javascript">
function copyAppendRow() {
var question = document.getElementById("question");
var clone=question.cloneNode(true);
var numberOfQuestions = $('.question').length;
var id = "question"+(numberOfQuestions);
clone.id=id;
var questiondiv = document.getElementById(id);
var h2s = questiondiv.getElementsByTagName("h2");
for(var h = 0; h < h2s.length; h++ ) {
h2s[h].innerHTML = "Question"+(numberOfQuestions); }
if($('#questionsuccess').css('display') == 'none'){
$('#questionsuccess').fadeIn('fast');
$('#questionsuccess').fadeOut(4000);
}
}
</script>
do you mean something like:
var divEle = document.getElementById("yourDivId");
var h2s = divEle.getElementsByTagName("h2");
for(var h = 0; h < h2s.length; h++ ) {
h2s[h].innerHTML = "Question"+(numberOfQuestions);
}
OR
jQuery way:
$("#"+yourDivId + " > h2").html("Question"+(numberOfQuestions));
I see from your first line that you are already using jQuery, so make life easy for yourself and use it to do this task.
$('#' + id + ' h2').html( 'Question ' + numberOfQuestions );
The jQuery selectors work just like CSS selectors. So this line of code finds the element with your variable id as its' id and gets all the h2 tags within that element. .html is a jQuery method that sets the inner HTML of an element.

Categories