this is a question link to another question I've already asked (see here: Sort list items from random child).
The problem is that I have a list of items that I want to split from a random item. I'm trying with "IndexOf()" but it returns always -1. Any ideas what I'm doing wrong?
Here is my code:
HTML
<ul class="myClass">
<li class="item">
<a href="URL" title="Company A" target="_blank">
<span class="logo">
<img src="images/logo1.jpg">
</span>
</a>
</li>
<li class="item">
<a href="URL" title="Company B" target="_blank">
<span class="logo">
<img src="images/logo2.jpg">
</span>
</a>
</li>
<li class="item">
<a href="URL" title="Company C" target="_blank">
<span class="logo">
<img src="images/logo3.jpg">
</span>
</a>
</li>
<li class="item">
<a href="URL" title="Company D" target="_blank">
<span class="logo">
<img src="images/logo4.jpg">
</span>
</a>
</li>
<li class="item">
<a href="URL" title="Company E" target="_blank">
<span class="logo">
<img src="images/logo5.jpg">
</span>
</a>
</li>
...
</ul>
JAVASCRIPT
function randomizeChild(){
var listItems = [];
$('ul.myClass li').each( function() {
listItems.push(this);
});
var randomChild = Math.round(Math.random() * listItems.length);
console.log("Random Child ---> " + randomChild);
var indexToSplit = listItems.indexOf(randomChild);
var first = listItems.slice(0, indexToSplit);
var second = listItems.slice(indexToSplit + 1);
console.log(indexToSplit); // it returns always -1 :(
console.log(first, second);
}
Your issue is you are getting the index which is an integer and checking the indexOf of the integer which doesn't exist in your array. You have an array of elements.
http://jsfiddle.net/h2a4L67k/
Try this:
function randomizeChild() {
var listItems = [];
$('ul.myClass li').each(function () {
listItems.push(this);
});
var randomChild = Math.round(Math.random() * listItems.length);
console.log("Random Child ---> " + randomChild);
var randomChildObject = listItems[randomChild];
var indexToSplit = listItems.indexOf(randomChildObject);
var first = listItems.slice(0, indexToSplit);
var second = listItems.slice(indexToSplit + 1);
console.log(indexToSplit); // it returns always -1 :(
console.log(first, second);
}
You don't even need to do what is above. You already have a random index so just use it right away:
function randomizeChild() {
var listItems = [];
$('ul.myClass li').each(function () {
listItems.push(this);
});
var randomIndex = Math.round(Math.random() * listItems.length);
console.log("Random Child ---> " + randomIndex);
var first = listItems.slice(0, randomIndex);
var second = listItems.slice(randomIndex + 1);
console.log(randomIndex); // it returns always -1 :(
console.log(first, second);
}
Fiddle: http://jsfiddle.net/h2a4L67k/1/
Related
I have a name card under a class and id named "column" . I have used the clone function with a for loop in JavaScript to increase the number of name cards so that i don't have to retype the code every time I create a new card. How do i access each name card and Enter/Edit the data inside each name card using JavaScript? Where ever i need to Enter data i have entered "DATA HERE" in the code below. At the moment I have 8 name cards using the clone property. As i am new to this, i don't know if this is the best way to do this. If there is a better way please let me know. Thanks a lot.
MAIN GOAL: i want to show different data in different name cards, but i don't want to rewrite the HTML code for each name card as the HTML code becomes very long. For example Name card 1 will have different data to name card 2.
$(document).ready(function() {
var e = $('.column');
for (var i = 0; i < 7; i++) {
e.clone().insertAfter(e);
e.clone[i].attr('id', 'clone' + i++);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="column" id="column">
<div class="container">
<div class="header"> <h3>"DATA HERE" </h3> </div>
<div class="location">
<h1><ion-icon class ="icon1" name="location-outline" class="nav__icon"></ion-icon> "DATA HERE" </h1>
</div>
<form method="post" > <p>
<button type="button" class="button3"> LIGHTS</button></a>
<button class="button">ON</button> </p>
</form>
<form method="post" > <p>
<button type="button" class="button2">OFF</button> </p>
</form>
<div class="icon-bar">
<a class="active" href="#">"DATA HERE"</a>
<a class="active" href="#">"DATA HERE" </a>
<a class="active" href="#">"DATA HERE"</a>
<a class="active" href="#">"DATA HERE"</a>
</div>
<div class="icon-bar2">
<a class="active" href="#"> "DATA HERE" </a>
<a class="active" href="#">"DATA HERE"</a>
<a class="active" href="#">"DATA HERE"</a>
</div>
</div>
</div>
OK now, you can use querySelectorAll to find the .column class, then you can set your code to each selector with it's index, starting from 0 to the 1st and ends with 7 in your case ..
here is an example for what i mean
try the snippet
EDIT: changed the snippet with all required areas.
here is an example of all content control on the 1st container, you can use what you need
Try the snippet.
$(document).ready(function() {
var e = $('.column');
for (var i = 0; i < 7; i++) {
e.clone().insertAfter(e);
}
//selecting the first Container with variables
const allcls = document.querySelectorAll('.column');
const chld = allcls[0].querySelector('.header > h3');
const chld2 = allcls[0].querySelector('.location > h1');
const chld3 = allcls[0].querySelectorAll('form');
const frmchld = chld3[0].querySelector('p :nth-child(2)');
const frmchld2 = chld3[1].querySelector('p :nth-child(1)');
const chld4 = allcls[0].querySelectorAll('.icon-bar .active');
const chld5 = allcls[0].querySelectorAll('.icon-bar2 .active');
/* set data for each element */
//.header text with new style
chld.innerText = "New Text for Header";
chld.style.color = 'gray';
chld.style.textAlign = 'center';
chld.style.margin = 'auto';
chld.style.padding = '1rem';
chld.style.background = 'darkblue';
chld.style.width = 'max-content';
chld.style.border = '1px solid darkgray';
//.location text with new color
chld2.innerText = 'Location text';
chld2.style.color = 'darkblue';
//ON button link + name
frmchld.setAttribute('onClick', '#NEWLINK_FOR_ON');
frmchld.innerText = "ON Button";
//off button link + name
frmchld2.setAttribute('onClick', '#NEWLINK2_FOR_ON');
frmchld2.innerText = "OFF Button";
//icon-bar links ( names + href )
chld4[0].innerText = "Iconbar Link1";
chld4[1].innerText = 'Iconbar link2';
chld4[2].innerText = 'Iconbar link3';
chld4[3].innerText = 'Iconbar link4';
chld4[0].setAttribute('href', '#Link_1');
chld4[1].setAttribute('href', '#Link_2');
chld4[2].setAttribute('href', '#Link_3');
chld4[3].setAttribute('href', '#Link_4');
//icon-bar2 links ( names + href )
chld5[0].innerText = "Iconbar2 Link1";
chld5[1].innerText = 'Iconbar2 link2';
chld5[2].innerText = 'Iconbar2 link3';
chld5[0].setAttribute('href', '#Link_1');
chld5[1].setAttribute('href', '#Link_2');
chld5[2].setAttribute('href', '#Link_3');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="column" id="column">
<div class="container">
<div class="header">
<h3>"DATA HERE" </h3>
</div>
<div class="location">
<h1>
<ion-icon class="icon1" name="location-outline" class="nav__icon"></ion-icon> "DATA HERE" </h1>
</div>
<form method="post">
<p>
<button type="button" class="button3"> LIGHTS</button>
<button class="button" onClick="#">ON</button> </p>
</form>
<form method="post">
<p>
<button type="button" class="button2" onClick="#">OFF</button> </p>
</form>
<div class="icon-bar">
<a class="active" href="#">"DATA HERE"</a>
<a class="active" href="#">"DATA HERE" </a>
<a class="active" href="#">"DATA HERE"</a>
<a class="active" href="#">"DATA HERE"</a>
</div>
<div class="icon-bar2">
<a class="active" href="#"> "DATA HERE" </a>
<a class="active" href="#">"DATA HERE"</a>
<a class="active" href="#">"DATA HERE"</a>
</div>
</div>
</div>
i dont know the final porpose of your problem, but i'm assuming you are trying to do that:
$(document).ready(function() {
var e = document.getElementById("column");
for (var i = 0; i < 7; i++) {
var newe=e.cloneNode(true);
document.body.insertAdjacentElement('beforeend', newe);
newe.id="column"+i;
}
hope it helps, probably you are learning but if the data comes from a database this workaround you are trying doing is usless (you will print trough a function this HTML.
Keep Growing, Plus Ultra!!!
I have this HTML template:
<div class="item">
<span class="light">Date</span>
<a class="link" href="">2018</a>
(4pop)
</div>
<div class="item">
<span class="light">From</span>
<span>
<a class="link" href="" title="Bob" itemprop="url"><span itemprop="name">Bob</span></a>,
</span>
<span>
<a class="link" href="" title="Peter" itemprop="url"><span itemprop="name">Peter</span></a>
</span>
</div>
<div class="item">
<span class="light">For</span>
<a class="link" href="">Bak</a>,
<a class="link" href="">Cam</a>,
<a class="link" href="">Oli</a>
</div>
<div class="item">
<span class="light">Nat</span>
<a class="link" href="">Cool</a>
</div>
</div>
And my Javascript code:
var doc = new DOMParser().parseFromString(HTMLContent,'text/html');
var infos = doc.evaluate('//div[#class="item"]/span[1]', doc, null, XPathResult.ANY_TYPE, null);
var nodes = [];
for(var node = infos.iterateNext(); node; node = infos.iterateNext()) {
nodes.push(node);
console.log(node.textContent);
// Until here, all things works well ! Except the code from here:
var nodde = node.nextElementSibling.attributes;
nodde.forEach(function(item){
console.log(item);
});
}
My goal is to get the respective value for each categorie, for example:
Date = 2018, (4pop)
From = Bob, Peter
For = Bak, Cam, Oli
Nat = Cool
I tried to iterate: node.nextElementSibling.attributes but without any success !
Is there a way to get the expected result please ?
The HTML Document Object Model, DOM, is preferred as it's easier. XPATH is geared toward more rigid XML documents.
Using JavaScript, you would get data with something like:
var users = document.querySelectorAll('[itemprop=name]').textContent;
console.log(users);
Problem: How do I clone each image from a list and "paste" them into another list?
I have searched but haven't found any solution close enough for my solution.
Short brief: I am creating a slideshow with thumbnails (jQuery-library: Slippry Slider). I want the thumbnails to work dynamicly, depending on the amount of slides.
So first I have some HTML containing the slides:
<ul id="thumbnails">
<li>
<a href="#slide1">
<img src="img/image-1.jpg" alt="This is caption 1">
</a>
</li>
<li>
<a href="#slide2">
<img src="img/image-2.jpg" alt="This is caption 2">
</a>
</li>
<li>
<a href="#slide3">
<img src="img/image-4.jpg" alt="And this is some very long caption for slide 4.">
</a>
</li>
Now I want to create wrapping elements for my thumbnails, first a div and then a ul-element:
// Create thumb-wrapping-elements
$('.demo_wrapper').append('<div class="thumb-box"></div>');
$('.thumb-box').append('<ul class="thumbs"></ul>');
And I want to check how many slides there is in the HTML above:
// How many thumbs? Check how many slides there is.
var count = $("#thumbnails li").length;
Create right numbers of li-elements and set the right width and values:
// Loop through and create li-elements and links
for (var thumbcounter = 0; thumbcounter < count; thumbcounter++) {
// Whats the width of each thumb?
var thumbwidth = (100/count) + '%';
thumburl = thumbcounter + 1;
$('.thumbs').append('<li><a href="#' + thumburl + '" data-slide="' + thumburl + '" style="width:' + thumbwidth + ';">
Here I would like to loop through each slide img from ul#thumbnails li a above and print them here. How the heck do I do that? :)
</a></li>');
};
See all code here: http://jborg.se/dev/slippry/demo/test.html
Now "a" is inside each a-element, just to make them visible.
Edit:
Made width of thumb more effective, thanks to answer below.
This is what I would like as output by the jQuery loop above (Right now I have everything right, except the images - which I do not know how to copy from the HTML and print here as each thumbnail):
<div class="thumb-box">
<ul class="thumbs">
<li>
<a href="#1" data-slide="1">
<img src="img/image-1.jpg" alt="This is caption 1">
</a>
</li>
<li>
<a href="#2" data-slide="2">
<img src="img/image-2.jpg" alt="This is caption 2">
</a>
</li>
<li>
<a href="#4" data-slide="3">
<img src="img/image-4.jpg" alt="And this is some very long caption for slide 4.">
</a>
</li>
</ul>
</div>
something like this?
$(document).ready(function() {
var html = '<div class="thumb-box"><ul class="thumbs"></ul></div>';
$('.demo').append(html);
var count = $("#thumbnails li").length;
var width = (100.00/count) + '%';
var counter = 0;
$('#thumbnails li').each(function() {
counter++;
var newItem = '<li>';
newItem += '<a href= "' + $(this).find('a').attr('href') + '" ';
newItem += 'data-slide="' + counter + '">';
newItem += '<img src="' + $(this).find('img').attr('src') + '" alt="' + $(this).find('img').attr('alt') + '"/>';
newItem += '</a></li>';
$('ul.thumbs').append(newItem);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
ORIGINAL<br/>
<ul id="thumbnails">
<li>
<a href="#1" data-slide="1">
<img src="img/image-1.jpg" alt="This is caption 1"/>
</a>
</li>
<li>
<a href="#2" data-slide="2">
<img src="img/image-2.jpg" alt="This is caption 2"/>
</a>
</li>
<li>
<a href="#4" data-slide="3">
<img src="img/image-4.jpg" alt="And this is some very long caption for slide 4."/>
</a>
</li>
</ul>
<br/>
DEMO
<div class="demo">
</div>
Try
// exported and edited the thumbwidth var for efficiency
var thumbwidth = (100/count) + '%';
// Loop through and create li-elements and links
for (var x = 0; x < count; x++) {
var imgEl = $('#thumbnails').find('img').eq(x).prop('outerHTML');
$('.thumbs').append('<li>'+ imgEl + '</li>');
}
PS- Sorry for no explanation and the mess, I'm on an iPad.
How do I add a link in the description of an index array in javascript? My code is below, thanks. I tried using push method, but I think I had a conflict with the showpic function. I really don't know, so I would appreciate any help.
<script type="text/javascript">
mypic = new Array();
mypic[0] = ["images/Lg_image1.jpg", "Large image 1 description."] //I want to add an HTML link to a website at the end of this array
mypic[1] = ["images/Lg_image2.jpg", "Large image 2 description."] //I want to add an HTML link to a website at the end of this array
function showpic2(n) {
document.getElementById("mainpic2").src = mypic[n][0]
document.getElementById("mycaption2").innerHTML = mypic[n][1]
count = n
}
count = 0;
function next() {
count++
if (count == mypic2.length) {
count = 0
}
document.getElementById("mainpic2").src = mypic2[count][0]
document.getElementById("mycaption2").innerHTML = mypic2[count][1]
}
function prev() {
count--
if (count < 0) {
count = mypic2.length - 1
}
document.getElementById("mainpic2").src = mypic2[count][0]
document.getElementById("mycaption2").innerHTML = mypic2[count][1]
}
</script>
<body>
<div id="container">
<div class="menu1">
<ul>
<li>Link 1 </li>
</ul>
<ul>
<li>Link 2 </li>
</ul>
</div>
<div id="large"> <img src="images/Lg_image1.jpg" class="mainpic2" id="mainpic2"> </div>
<div id="thumbs2"> <img src="images/sm_image1.jpg" alt="image1"/> <img src="images/sm_image2.jpg" alt="image2"/> </div>
<div id="mycaption2">Large image default description. </div>
<div id="logohome"> <img src="images/#.png" alt="" /> </div>
<div id="homebox"> <img src="images/homebox1.png" alt="" /> </div>
</div>
</body>
</html>
<script type="text/javascript">
mypic = [];
mypic.push({address:"images/Lg_image1.jpg", desc: "Large image 1 description."});
function showpic2(n) {
document.getElementById("mainpic2").src = mypic['address']
document.getElementById("mycaption2").innerHTML = mypic['desc']
count = n
}
</script>
something like this
I don't know what problems you had with .push() but this should work:
mypic[0].push("<a href='link.html'>I am a link</a>");
And of course the same can be done with mypic[1].
I have a div that contains a few pictures, using javascript i scroll left and right in that div, my problem is that for some reason in firefox the values are different that in chrome (works fine):
function scroll_right() {
document.getElementById('left').style.opacity = '1';
document.getElementById('left').style.filter = 'alpha(opacity=100)';
document.getElementById('scroller').scrollLeft += PixelPerInterval;
if (!stop) t = setTimeout('scroll_right()', 10);
else stop = false;
scrX = document.getElementById('scroller').scrollLeft;
pwidth = document.getElementById('cont').clientWidth;
awidth = document.getElementById('cont').scrollWidth;
//document.getElementById('type').innerHTML = scrX + ' ' + (awidth-pwidth);
if (scrX >= awidth - pwidth) {
//type.innerHTML = scrX + ' right';
document.getElementById('right').style.opacity = '0.4';
document.getElementById('right').style.filter = 'alpha(opacity=40)';
}
}
using scroll_left it's easy, just have scrX = 0.
The outer container is called scroller its width is fixed, and the inner container is called cont and its width isn't set by the user so unlimited pictures can be entered.
Any ideas? (without using jquery).
thanks alot.
Btw html code:
<img src="left.png" id="left" onmouseover="scroll_left();" onmouseout="stop_scroll();" />
<div id="scroller">
<div id="cont">
<a onclick="main(this);" href="#">
<img class="thumb" id="persp" src="sport/911-persp.png" alt="persp" />
</a>
<a onclick="main(this);" href="#">
<img class="thumb" id="side" src="sport/911-side.png" alt="side" />
</a>
<a onclick="main(this);" href="#">
<img class="thumb" id="front" src="sport/911-front.png" alt="front" />
</a>
</div>
</div>
<img src="right.png" id="right" onmouseover="scroll_right();" onmouseout="stop_scroll();" />