js sort by id on button - javascript

http://jsfiddle.net/fkling/nXkDp/
Hi, im trying to hookup this script onto button, but it's not working. i have no idea why.
var sortID = function()
{
var toSort = document.getElementById('list').children;
toSort = Array.prototype.slice.call(toSort, 0);
toSort.sort(function(a, b) {
var aord = +a.id.split('-')[1];
var bord = +b.id.split('-')[1];
// two elements never have the same ID hence this is sufficient:
return (aord > bord) ? 1 : -1;
});
var parent = document.getElementById('list');
parent.innerHTML = "";
for(var i = 0, l = toSort.length; i < l; i++) {
parent.appendChild(toSort[i]);}
};

Create a button and onload, assign it's onclick handler to your sortID() function:
jsFiddle Demo
HTML:
<input type="button" id="mybutton" value="Sort" />
Javascript:
var sortID = function () {
var toSort = document.getElementById('list').children;
toSort = Array.prototype.slice.call(toSort, 0);
toSort.sort(function (a, b) {
var aord = +a.id.split('-')[1];
var bord = +b.id.split('-')[1];
// two elements never have the same ID hence this is sufficient:
return (aord > bord) ? 1 : -1;
});
var parent = document.getElementById('list');
parent.innerHTML = "";
for (var i = 0, l = toSort.length; i < l; i++) {
parent.appendChild(toSort[i]);
}
};
window.onload = function(){
document.getElementById("mybutton").onclick = sortID;
}

Try this :
HTML :
<div id="list">
<div id="categorie5.1-4">4</div>
<div id="categorie5.1-3">3</div>
<div id="categorie5.1-5">5</div>
<div id="categorie5.1-1">1</div>
<div id="categorie5.1-2">2</div>
</div>
<input type="button" onclick="keyMe()" value="hook">
Javascript :
function keyMe(){
var toSort = document.getElementById('list').children;
toSort = Array.prototype.slice.call(toSort, 0);
toSort.sort(function(a, b) {
var aord = +a.id.split('-')[1];
var bord = +b.id.split('-')[1];
// two elements never have the same ID hence this is sufficient:
return (aord > bord) ? 1 : -1;
});
var parent = document.getElementById('list');
parent.innerHTML = "";
for(var i = 0, l = toSort.length; i < l; i++) {
parent.appendChild(toSort[i]);
}
}
I hope it will help you
here is the link : jsfiddle.net/dp6Vr/

You can assign an event handler to a button as follows:
document.getElementById('sortButtonIdHere').addEventListener('click', function() {
// your code here
}, false);
Demo: http://jsfiddle.net/nXkDp/31/
If you're concerned about supporting IE8 and older, you could use:
document.getElementById('sortButtonIdHere').onclick = function() {
// your code here
};
Or you could add a test for whether .addEventListener() is defined and if not use attachEvent() as explained at MDN.

Related

Javascript: Clicking an injected button doesn't work

when I inject some code the onclick doesn't work
here is the code I use.
document.getElementById('headbar').onclick = function() {
var list_div_preleva = document.getElementsByClassName('preleva_dati').length;
var list = document.getElementsByClassName('box_commenti');
for(var i = list_div_preleva; i < list.length; i++) {
var parentDiv = list[i].parentNode.id;
var id_post = document.getElementById(parentDiv);
var creaelementodiv = document.createElement("button");
creaelementodiv.className = "preleva_dati";
creaelementodiv.setAttribute("id", "blocco_dati");
creaelementodiv.innerHTML = "<li>preleva il post</li>";
id_post.appendChild(creaelementodiv);
}
};
<div id="headbar">div</div>
when the code is inside, onclick doesn't work
<!-- begin snippet: js hide: false console: true babel: false -->
document.getElementById('blocco_dati').onclick = function() {
alert(11);
};
can the problem be solved?
document.getElementById('headbar').onclick = function() {
var id_post = document.getElementById("headbar2");
var creaelementodiv = document.createElement("button");
creaelementodiv.className = "preleva_dati";
creaelementodiv.setAttribute("id", "blocco_dati");
creaelementodiv.innerHTML = "preleva il post";
creaelementodiv.setAttribute("onclick", "doSomething();");
id_post.appendChild(creaelementodiv);
};
function doSomething() {
alert(11);
};
<div id="headbar">div</div>
<div id="headbar2"></div>
You can set one more attribute while injecting element
for ex:
creaelementodiv.setAttribute("onclick", "doSomething();");
and then you can call that function like
function doSomething() {
alert(11);
};

TypeError: Cannot read property 'innerText' of undefined - Deleting from eshop

I need to get help here.
I'm working on my eshop. All is working fine except removing a object from the cart. When I do it, the price is not changed. And in the console it's written:
"Uncaught TypeError: Cannot read property 'innerText' of undefined at updateCelkoveCeny (Eshop.js:86)
That 86 row is the row with parseFloat(). Any suggestions?
function updateCelkoveCeny() {
var produktyKosikContainer = document.getElementsByClassName('kosik-produkty')[0]
var radkyKosik = produktyKosikContainer.getElementsByClassName('kosik-radek')
var celkovaCena = 0
for (var i = 0; i < radkyKosik.length; i++) {
var radekKosik = radkyKosik[i]
var cenaElement = radekKosik.getElementsByClassName('kosik-cena')[0]
var pocetElement = radekKosik.getElementsByClassName('kosik-pocet-input')[0]
var cena = parseFloat(cenaElement.innerText.replace(',-', ''))
var pocet = pocetElement.value
celkovaCena = celkovaCena + (cena * pocet)
}
document.getElementsByClassName('kosik-celkem-cena')[0].innerText = celkovaCena + ",-"
}
Edit: This is element, which i add, if user want to add a new product to cart.
function pridejPoKliknutiDoKosiku(event) {
var button = event.target
var produkt = button.parentElement.parentElement
var nazevProduktu = produkt.getElementsByClassName('eshop-nazev-produktu')[0].innerText
var cena = produkt.getElementsByClassName('eshop-cena-produktu')[0].innerText
var zdrojObrazku = produkt.getElementsByClassName('eshop-fotka-produktu')[0].src
pridejProduktDoKosiku(nazevProduktu, cena, zdrojObrazku)
updateCelkoveCeny()
}
function pridejProduktDoKosiku(nazevProduktu, cena, zdrojObrazku) {
var radekKosik = document.createElement('div')
radekKosik.classList.add('kosik-radek')
var kosikProdukty = document.getElementsByClassName('kosik-produkty')[0]
var NazvyProduktu = kosikProdukty.getElementsByClassName('kosik-nazev-produktu')
for (var i = 0; i < NazvyProduktu.length; i++) {
if (NazvyProduktu[i].innerText == nazevProduktu) {
alert("Tento produkt je již obsažen v košíku.")
return
}
}
var radekKosikKontent = `
<div class="kosik-radek">
<div class="kosik-produktu kosik-sloupec">
<img class="kosik-fotka-produktu" src="${zdrojObrazku}" width="100" height="100"><br>
<span class="kosik-nazev-produktu">${nazevProduktu}</span>
</div>
<span class="kosik-cena kosik-sloupec">${cena}</span>
<div class="kosik-pocet kosik-sloupec">
<input class="kosik-pocet-input" type="number" value="1" min="1">
<button class="button-remove" type="button">Odstranit</button>
</div>
</div><br><br>`
radekKosik.innerHTML = radekKosikKontent
kosikProdukty.append(radekKosik)
radekKosik.getElementsByClassName("button-remove")[0].addEventListener('click', odstranitProduktyVKosiku)
radekKosik.getElementsByClassName('kosik-pocet-input')[0].addEventListener('change', pocetZmenen)
}
Is there an element in your DOM that contains class 'kosik-cena'? If so, you could loop over the array to get the innerText. Most likely there is no element found with class 'kosik-cena'. This way it is not possible to get the innerText of an element that doesn't exist. It would be nice to give some insights into your HTML.
Get the innerText of an array of elements:
var cenaElement = document.getElementsByClassName("kosik-cena");
for (var i = 0; i < cenaElement.length; i++) {
var text = cenaElement[i].innerText;
console.log(text);
}

How get next element after "this" - pure javascript

I have code:
var links = document.querySelectorAll('a[data-lightbox]');
for (var i = 0; i < links.length; i++) {
links[i].addEventListener('click', function() {
event.preventDefault();
var imgLink = this.getAttribute('href');
var imgTitle = this.getAttribute('title');
var dataLightbox= this.getAttribute('data-lightbox');
console.log(); //next element after "this." something like "links[i+1]" or i don't know...
}, false);
}
I want to get 'data-lightbox' attribute for next element which I clicked currently. How to do it?
Using a IIFE can do the trick to preserve the i scope
var links = document.querySelectorAll('a[data-lightbox]');
for (var i = 0; i < links.length; i++) {
(function(i){
links[i].addEventListener('click', function() {
event.preventDefault();
var imgLink = this.getAttribute('href');
var imgTitle = this.getAttribute('title');
var dataLightbox= this.getAttribute('data-lightbox');
console.log(links[i + 1]);
}, false);
})(i)
}
This is a scope issue.
You can use bind (which would fix the scope issue) for the onclick event binding,while this you can send i to the method and you can access the next element using i+1
check the following snippet
window.onload = function() {
var links = document.querySelectorAll('a[data-lightbox]');
for (var i = 0; i < links.length; i++) {
links[i].addEventListener('click', onclick.bind(links[i], i));
}
function onclick(i) {
var imgLink = this.getAttribute('href');
var imgTitle = this.getAttribute('title');
var dataLightbox = this.getAttribute('data-lightbox');
if(links[i+1]!=undefined){
var nextLightbox = links[i + 1].getAttribute('data-lightbox');
}
console.log(imgLink);
console.log(dataLightbox);
console.log(nextLightbox);
}
}
<a href="#" data-lightbox=10>link1</a>
<a href="#" data-lightbox=20>link2</a><a href="#" data-lightbox=30>link3</a><a href="#" data-lightbox=40>link4</a><a href="#" data-lightbox=50>link5</a>
Hope it helps
You can try to get the next element in the way you thought: links[i + 1], although the i is an unique hoisted variable by this loop. You can, however, re-generate this i in the loop body, using variable declaration of let (only supported in ES6+) or using a new function scope inside that loop.
let acts like we were in a new scope, but not. It won't affect the previous i in this example, it'll only replace its presence at the block statement.
var links = document.querySelectorAll('a[data-lightbox]');
for (var i = 0; i < links.length; i++) {
let i = i;
links[i].addEventListener('click', function() {
event.preventDefault();
var imgLink = this.getAttribute('href');
var imgTitle = this.getAttribute('title');
var dataLightbox= this.getAttribute('data-lightbox');
console.log(links[i + 1]);
}, false);
}
In addition to what others have mentioned, another way to go about this is using nextSibling on this.
var links = document.querySelectorAll('a[data-lightbox]');
for (var i = 0; i < links.length; i++) {
links[i].addEventListener('click', function() {
event.preventDefault();
var imgLink = this.getAttribute('href');
var imgTitle = this.getAttribute('title');
var dataLightbox= this.getAttribute('data-lightbox');
console.log(this.nextElementSibling);
}, false);
}

How to ssign Variable with div element's name

So I got multiple divs with different images embedded. Each one has its unique name attributes. I'm trying to apply the hover effect to each divs by changing the image source. I don't want to write multiple scripts, rather I'm trying to write a just one block of script that would effect every div.
<div id="div1" >
<img id="img1" name="img1" src="img1_up.jpg" />
</div>
<div id="div2">
<img id="img2" name="img2" src="img2_up.jpg" />
</div>...and so on
Now here is the script that I currently have for the rollover effects
<script>
var var1 = document.getElementById("div1");
var1.addEventListener("mouseover", changeImage1);
var1.addEventListener("mouseout", restoreImage1);
function changeImage1() {
document.getElementById("img1").src = "img1_ro.jpg";
}
function restoreImage1() {
document.getElementById("img1").src = "img1_up.jpg";
}
var var2 = document.getElementById("div2");
var2.addEventListener("mouseover", changeImage2);
var2.addEventListener("mouseout", restoreImage2);
function changeImage2() {
document.getElementById("img2").src = "img2_ro.jpg";
}
function restoreImage2() {
document.getElementById("img2").src = "img2_up.jpg";
}...and so on
</script>
I would like to use the name attributes from each images to create dynamic code to apply to all images. Here is what I have in mind but not sure the exact way to write it. PLEASE HELP
...
var dynamicVar = ????
dynamicVar.addEventListener("mouseover", changeImage();
dynamicVar.addEventListener("mouseout", restoreImage();
function changeImage() {
document.getElementById(dynamicVar).src = dynamicVar + "_ro.jpg";
}
function restoreImage() {
document.getElementById(dynamicVar).src = dynamicVar + "_up.jpg";
}
You can use loop to add event, don't need to specify id for each div:
var inputs = document.getElementsByTagName("div");
for(var i = 0; i < inputs.length; i++) {
if(inputs[i].id.indexOf('div') >= 0) {
inputs[i].addEventListener("mouseover", changeImage);
inputs[i].addEventListener("mouseout", restoreImage);
}
}
function changeImage(){
var tmpStr = this.id;
var divIndex = tmpStr.substring(3, tmpStr.length);
document.getElementById("img" + divIndex).src = divIndex + "_ro.jpg";
}
function restoreImage(){
var tmpStr = this.id;
var divIndex = tmpStr.substring(3, tmpStr.length);
document.getElementById("img" + divIndex).src = divIndex + "_up.jpg";
}
See on fiddle: Link
try this
var parent = document.getElementById("parent");
var childs = parent.getElementsByTagName('div');
for (var i = 0; i < childs.length; i++) {
(function () {
var e = childs[i];
e.addEventListener("mouseover", function () {
changeImage(e);
});
e.addEventListener("mouseout", function () {
restoreImage(e);
});
}());
}
function changeImage(element) {
var imgs = element.getElementsByTagName('img');
for (var i = 0; i < imgs.length; i++) {
alert(imgs[i].id);
}
}
function restoreImage(element) {
var imgs = element.getElementsByTagName('img');
for (var i = 0; i < imgs.length; i++) {
imgs[i].src = img_ro;
}
}
you can check this fiddle

How to add index and value to a object?

How to add index and value to a object, below is my code, I tried to add index and value in loop, but it shows error undefined is not an object ($data.file_list_image.i.sequence), why and how to solve it ?
tried to get json data and send to server side
desire data
$data = {file_list_image: {0: {sequence: 1, intro: }, 1: {sequence: 1, intro: }, }}
js
var $el = $content_list.find('.content-list-gallery-file-list');
var file_length = $el.length;
var file_image_length = 0;
var file_embed_youtube_length = 0;
for (var i = 0; i < file_length; i++) {
if ($el.eq(i).attr('data-type') == 0) { // console.log('img');
file_image_length++;
} else if ($el.eq(i).attr('data-type') == 1) { // console.log('video');
file_embed_youtube_length++;
}
}
var $data = {};
for (var i = 0; i < file_image_length; i++) {
var $file_list = $el.filter(function () {
return $(this).attr('data-type') == 0 && $(this).attr('data-tmp-id') == i;
});
var sequence = $file_list.attr('data-sequence');
var intro = $file_list.find('.intro textarea').val();
$data.file_list_image.i.sequence = sequence;
$data.file_list_image.i.intro = intro;
}
console.log($data);
HTML
<div class="content_list">
<div class="content-list-gallery-file-list" data-type="0" data-tmp-id="1" data-sequence="0">
<div class="intro"><textarea></textarea></div>
</div>
<div class="content-list-gallery-file-list" data-type="0" data-tmp-id="0" data-sequence="1">
<div class="intro"><textarea></textarea></div>
</div>
<div class="content-list-gallery-file-list" data-type="1" data-tmp-id="2" data-sequence="2">
<div class="intro"><textarea></textarea></div>
</div>
</div>
Example of how it can be done by initializing object properties at correct time:
Fiddle example
var $data = {};
$data.file_list_image = {};
for (var i = 0; i < 5; i++)
{
$data.file_list_image[i] = {};
$data.file_list_image[i]["sequence"] = "seq" + i;
$data.file_list_image[i]["intro"] = "in" + i;
}
console.log($data);
By the way, $data.file_list_image[i]["sequence"] (same with intro) can also be $data.file_list_image[i].sequence
Fiddle example with original HTML.

Categories

Resources