I don't want to use jQuery, or any other 3rd party library!
Not working proof of concept:
<div id="Wrapper"></div>
<script>
function Build()
{
for (var i = 0 ; i < 10 ; i++)
{
var elem = document.createElement("div");
elem.setAttribute("onclick", "OnClickEvent(" + i + ")");
elem.textContent = "Hi";
document.getElementById("Wrapper").appendChild(elem);
}
}
function OnClickEvent(elementNum)
{
alert("Hi! I am " + elementNum);
}
Build();
</script>
fiddle: http://jsfiddle.net/qyzrQ/
In real life:
I'm dynamically creating a table based on ajax callback, each row contains an image button and another table. This image button should be able to hide or show corresponding inner table.
Frustrating. I was able to solve it myself.
It is enough to add (even before inserrting it into DOM):
element.setAttribute("onclick","functionName("+param+")");
Here is what i wanted to get: http://jsfiddle.net/YhY4Q/6/
And prototype (in case fiddle got deleted):
html:
<section id="Table" class="table">
<header class="row">
<div class="cell">header</div>
</header>
<script>
function ToggleShow(id) {
var elem = document.getElementById(id);
if (elem.classList.contains("invisible")) {
elem.classList.remove("invisible");
} else {
elem.classList.add("invisible");
}
}
</script>
<section id="TableWrapper">
</section>
</section>
javascript:
function ToggleShow(id) {
var elem = document.getElementById(id);
if (elem.classList.contains("invisible")) {
elem.classList.remove("invisible");
} else {
elem.classList.add("invisible");
}
}
function Build() {
var parent = document.getElementById("TableWrapper");
for (var id = 0; id < 10; id++) {
var row = document.createElement("div");
row.appendChild(HeaderRowBuilder(id));
row.appendChild(InnerTableBuilder(id));
parent.appendChild(row);
}
}
function HeaderRowBuilder(id) {
var header = document.createElement("header");
header.classList.add("row");
header.appendChild(HeaderCellBuilder(id));
var strongEle = document.createElement("strong");
strongEle.classList.add("cell");
strongEle.classList.add("cell2");
strongEle.textContent = "Something else";
header.appendChild(strongEle);
return header;
}
function HeaderCellBuilder(id) {
var div = document.createElement("div");
div.classList.add("cell");
div.appendChild(HeaderImageBuilder(id));
return div;
}
function HeaderImageBuilder(id) {
var img = document.createElement("img");
img.setAttribute("alt", "extended");
img.setAttribute("onclick", "ToggleShow('InnerTable_" + id + "')");
return img;
}
function InnerTableBuilder(id) {
var div = document.createElement("div");
div.setAttribute("id", "InnerTable_" + id);
div.textContent = "More rows, I don't care about them right now";
return div;
}
Build();
and css:
.table {
display: table;
}
.table .cell {
display: table-cell;
}
.table .cell2 {
border: 1px solid black;
width: 100%;
}
.table .spacer {
min-width: 40px;
max-width: 40px;
}
.table .cell3 {
min-width: 50px;
max-width: 50px;
}
.table .row {
display: table-row;
}
.invisible {
display: none;
}
Related
I am trying to append my variables 'showName' and 'showDescription' to the 'results' div object. I have tried to add them in using 'innerHTML' but I just get the description shown. I have tried making additional divs to put INSIDE the 'results' div but that didn't work either.
I want the 'showName' to appear above the 'showDescription in the div.
I am challenging myself to not use JQuery so that is not a viable option.
code:
document.querySelector('.search').addEventListener('keypress', function(e){//On button click of enter, get the value of the search bar and concatanate it to the end of the url
if(e.key==='Enter'){
var query = document.getElementById('main').value;
var url = fetch("http://api.tvmaze.com/search/shows?q="+query) //use fetch to get the data from the url, THEN convert it to json THEN console.log the data.
.then(response => response.json())
.then(data => {
console.log(data)
var domObject = document.createElement('div')
domObject.id="myDiv";
domObject.style.width="800px";
domObject.style.height="5000px";
domObject.style.display="flex";
domObject.style.flexDirection="column";
domObject.style.margin="auto";
domObject.style.borderRadius="30px";
domObject.style.background="";
document.body.appendChild(domObject);
for (var i = 0; i < data.length; i++) { //for all the items returned, loop through each one and show the name of the show and the dsescription of the show.
var showName = data[i].show.name;
//console.log(showName);
var showDescription = data[i].show.summary
//console.log(showDescription);
var results = document.createElement('div')
results.id="myResults";
results.style.width="600px"
results.style.height="400px";
results.style.background="white";
results.style.margin="auto";
results.style.borderRadius="30px";
results.style.fontFamily="Poppins"
results.style.display="flex";
results.style.flexDirection="column";
results.innerHTML=showName;
results.innerHTML=showDescription;
document.getElementById("myDiv").appendChild(results);
}
})
}
});
document.querySelector('.search').addEventListener('keydown', function(o){
if(o.key==='Backspace'){
location.reload();
}
});
result of searching in 'car'
results.innerHTML = showName;
results.innerHTML = showDescription;
With this you are overwriting showName with showDescription.
What you need to do is concatenate with +=.
Also, it will be much easier to replace this:
domObject.style.width = "800px";
domObject.style.height = "5000px";
domObject.style.display = "flex";
domObject.style.flexDirection = "column";
domObject.style.margin = "auto";
domObject.style.borderRadius = "30px";
domObject.style.background = "";
with domObject.classList.add('some-class');
and CSS will be:
.some-class {
width: 800px;
height: 500px;
// etc...
}
Moved your code to a working example.
Note: because of authors styles, it is only possible to run snippet in fullscreen. =)
const dosearch = () => {
var query = document.getElementById('main').value;
var url = fetch("https://api.tvmaze.com/search/shows?q=" + query)
.then(response => response.json())
.then(data => {
const myDiv = document.getElementById("myDiv");
myDiv.innerHTML = ''; // <---- this is for testing
for (var i = 0; i < data.length; i++) {
var showName = data[i].show.name;
var showDescription = data[i].show.summary
var results = document.createElement('div');
results.className = 'myResults';
var header = document.createElement('h2');
header.innerHTML = showName;
results.appendChild(header);
var desc = document.createElement('div');
desc.innerHTML = showDescription;
results.appendChild(desc);
myDiv.appendChild(results);
}
});
}
document.querySelector('.search').addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
dosearch();
}
});
#myDiv {
width: 800px;
height: 5000px;
display: flex;
flex-direction: column;
margin: auto;
border-radius: 30px;
background: black;
}
.myResults {
width: 600px;
height: 400px;
background: white;
margin: auto;
border-radius: 30px;
font-family: Poppins;
display: flex;
flex-direction: column;
}
.myResults p, .myResults h2 {
margin: 1em;
}
<input type="text" id="main" class="search" style="margin-bottom: 4px" value="Car" /><button onclick="dosearch()">Go</button>
<div id="myDiv"></div>
I am trying to make an interface where you can select tickets and buy them, I want that when I click on a seat it displays like "You are currently buying the next tickets + (The tickets chosen by the user)".
This is my code so far:
var seatsUnclicked = document.getElementsByClassName("seat-unique");
var seatsClicked = document.getElementsByClassName("seatClicked");
var images = document.getElementsByTagName("IMG");
var seatsOutput = document.getElementsById("seatsOutput");
var ticketsData = 0
for (let i = 0; i < seatsUnclicked.length; i++) {
seatsUnclicked[i].onmouseover = function() {
this.src = "chairclicked.svg";
this.onmouseout = function() {
this.src = "chair.svg"
}
if ($(this).hasClass('seatClicked')) {
this.src = "chairclicked.svg";
this.onmouseout = function() {
this.src = "chairclicked.svg"
}
}
}
seatsUnclicked[i].onclick = function() {
this.classList.add("new")
if ($(this).hasClass('seatClicked')) {
this.classList.remove("seatClicked")
this.classList.remove("new")
this.src = "chair.svg";
this.onmouseout = function() {
this.src = "chair.svg"
}
ticketsData = ticketsData - /* "the id of this element in a string" */
}
if ($(this).hasClass('new')) {
this.src = "chairclicked.svg";
this.classList.add("seatClicked")
this.classList.remove("new")
this.onmouseout = function() {
this.src = "chairclicked.svg"
}
ticketsData = ticketsData + /* "the ID of this element in a string" */
}
seatsOutput.innerHTML = "THE TICKETS YOU HAVE CHOSEN ARE" + string(ticketsData)
}
}
<div class="seats-row-A">
<img id="A1" class="seat-unique " src="http://via.placeholder.com/100x100?text=A1">
<img id="A2" class="seat-unique " src="http://via.placeholder.com/100x100?text=A2">
<img id="A3" class="seat-unique " src="http://via.placeholder.com/100x100?text=A3">
<img id="A4" class="seat-unique " src="http://via.placeholder.com/100x100?text=A4">
<img id="A5" class="seat-unique" src="http://via.placeholder.com/100x100?text=A5">
<img id="A6" class="seat-unique " src="http://via.placeholder.com/100x100?text=A6">
<img id="A7" class="seat-unique " src="http://via.placeholder.com/100x100?text=A7">
</div>
<h2 id="seatsOutput">Chosen Tickets:</h2>
jQuery
The only jQuery statement in OP code is: $(this).hasClass('seatClicked').
The plain JavaScript equivalent is: this.classList.contains('seatClicked').
Question
I couldn't follow the OP code because there was only a class, an id, and img tags that match the JavaScript, but it's not that clear because of the *.svg files (not provided.) Also, there's a curly bracket } missing (I think it belongs to the for loop, but I'm not wasting time on debugging typos.)
The Demo was built in mind with what the question and comments had mentioned:
"...I want that when I click on a seat it displays like "You are currently buying..."
Highlight icon when hovered over.
Reveal icon's id when hovered on.
All hover behavior is done with CSS: :hover, ::before, ::after, content: attr(id), content: '\a0\1f4ba'. Using JavaScript for behavior CSS can do will result in more CPU cycles. CSS will use GPU of your graphics card instead of the CPU.
Testing
The seats are dynamically generated with id="A* by entering a number in the input and clicking the View button. For each additional click of the button a new batch of seats are appended and have ids that correspond to it's group:
input: 55 and first click A0-A55,
input: 12 and second click B0-B12,
input: 222 and third click C0-C222
...
Last group is J
References
The Demo is basically a <form>. HTMLFormControlsCollection API is used to set/get form controls and values.
Reference the tag
const ui = document.forms.tickets;
This is a collection of all form controls in form#tickets
const t = ui.elements;
Now all form controls are now accessible by prefixing a form control's #id or [name] with the HTMLFormControlsCollection Object.
<textarea name='textA'></textarea>
Without HFCC API
var ta = document.querySelector('[name=textA]');
With HFCC API
var ta = t.textA;
The links are collected by Links Collection.
document.links
DocumentFragment is used to insert a huge amount of dynamic HTML in one shot efficiently and quickly.
document.createDocumentFragment();
Various array methods were used:
Array.from()
map()
fill()
indexOf()
Demo
const ui = document.forms.tickets;
const t = ui.elements;
const seats = document.getElementById('seats');
t.btn.addEventListener('click', seatsAvailable);
seats.addEventListener('click', function(e) {
let picked = [];
pickSeat(e, picked);
}, false);
function pickSeat(e, picked) {
const display = t.display;
if (e.target.tagName === "A") {
e.target.classList.toggle('picked');
picked = Array.from(document.querySelectorAll('.picked'));
}
picked = picked.map(function(seat, index, picked) {
return seat.id;
});
display.value = "";
display.value = picked;
}
function seatsAvailable(e) {
const qty = this.previousElementSibling;
const last = document.links[document.links.length - 1].id;
console.log(last);
const limit = parseInt(qty.value, 10) + 1;
const spots = new Array(limit);
spots.fill(0, 0, limit);
return generateSeats(spots, last);
}
function generateSeats(spots, last) {
if (last.charAt(0) === "J") {
t.display.textContent += "Last row available";
return false;
}
const rowID = ['x', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'];
let row = rowID.indexOf(last.charAt(0)) + 1;
const frag = document.createDocumentFragment();
const avSeats = spots.map(function(A, idx) {
const seat = document.createElement('a');
seat.id = rowID[row] + idx;
seat.href = "#/";
frag.appendChild(seat);
return seat;
});
seats.appendChild(frag);
if (document.links[0].id === 'x') {
const x = document.getElementById('x');
x.parentElement.removeChild(x);
}
if (document.links.length > 114) {
const ext = (Math.round(document.links.length / 114)*600)+600;
seats.style.maxHeight = ext+'px';
}
return avSeats;
}
html,
body {
width: 100%;
height: 10%;
font: 400 16px/1.3 Consolas;
}
#seats {
display: flex;
flex-flow: column wrap;
max-height: 600px;
width: auto;
border: 3px ridge grey;
}
.box {
display: table
}
input,
button,
label {
font: inherit
}
#qty {
text-align: right
}
#display {
display: table-cell;
}
.tag {
overflow-x: scroll;
overflow-y: hidden;
display: block;
width: 400px;
line-height: 1.3
}
a,
a:link,
a:visited {
display: inline-block;
margin: 0;
text-align: center;
text-decoration: none;
transition: all 500ms ease;
}
a:hover,
a:active {
background: rgba(0, 0, 0, 0);
color: #2468ac;
box-shadow: 0 0 0 3px #2468ac;
}
a::before {
content: attr(id);
color: transparent;
}
a:hover::before {
color: #2468ac;
}
a.picked::before {
color: #000;
}
a::after {
content: '\a0\1f4ba';
font-size: 1.5rem;
}
#x {
pointer-events: none
}
.as-console-wrapper {
width: 30%;
margin-left: 70%
}
<form id='tickets'>
<fieldset class='box'>
<legend>Available Seats</legend>
<fieldset class='box'>
<input id='qty' type='number' min='0' max='50' value='1'> <button id='btn' type='button'>View</button>
<label class='tag'>Current ticket purchases to seats:
<output id='display'></output>
</label>
</fieldset>
<section id='seats'>
<a id='x' href='#/'></a>
</section>
</fieldset>
</form>
I have been trying to create a system that when I hover over a specific div, specific text relating to that div appears. Each div is in the same class, with info at a different div with corresponding indexes. I was wondering if there was any way that I could get the class index of each div by hovering over them in order to show hidden information about them. (by showing the hidden info divs).
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
var allPeople = [];
function win (name, info){
this.name = name;
this.info = info;
}
allPeople[0] = new win ("Shelly", "Is Cool");
allPeople[1] = new win ("Brandon", "Likes to golf");
allPeople[2] = new win ("Steve", "Plays Football");
allPeople[3] = new win ("Mia", "Is a good cook");
var i = 0;
$('document').ready(function(){
for (i = 0; i < allPeople.length; i++){
$("body").append("<div class='people'> " + allPeople[i].name +" </div>");
}
for (i = 0; i < allPeople.length; i++){
$("body").append("<div class='info'> " + allPeople[i].info +" </div>");
}
});
</script>
<style>
body {
background-color: lightblue;
}
div {
background-image: url("http://themes.wdfiles.com/local--files/semi-trans/semi-transbgtransparent.png");
color: white;
padding: 2%;
margin: 2%;
border: 3px white solid;
}
.info {
display: none;
border-color: red;
}
</style>
</head>
<body>
</body>
</html>
A simple solution can be based on saving the index of each div at creation time as a data attribute like:
$("body").append("<div class='people' data-index='" + i +"'> " + allPeople[i].name +" </div>");
var allPeople = [];
function win (name, info){
this.name = name;
this.info = info;
}
allPeople[0] = new win ("Shelly", "Is Cool");
allPeople[1] = new win ("Brandon", "Likes to golf");
allPeople[2] = new win ("Steve", "Plays Football");
allPeople[3] = new win ("Mia", "Is a good cook");
var i = 0;
$('document').ready(function(){
for (i = 0; i < allPeople.length; i++){
$("body").append("<div class='people' data-index='" + i +"'> " + allPeople[i].name +" </div>");
}
for (i = 0; i < allPeople.length; i++){
$("body").append("<div class='info' data-index='" + i +"'> " + allPeople[i].info +" </div>");
}
$('.people').hover(function(e) {
$('.info').eq($(this).data('index')).show();
}, function(e) {
$('.info:visible').hide();
});
});
body {
background-color: lightblue;
}
div {
background-image: url("http://themes.wdfiles.com/local--files/semi-trans/semi-transbgtransparent.png");
color: white;
padding: 2%;
margin: 2%;
border: 3px white solid;
}
.info {
display: none;
border-color: red;
}
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
You can use jQuery.index():
var allPeople = [];
function win (name, info){
this.name = name;
this.info = info;
}
allPeople[0] = new win ("Shelly", "Is Cool");
allPeople[1] = new win ("Brandon", "Likes to golf");
allPeople[2] = new win ("Steve", "Plays Football");
allPeople[3] = new win ("Mia", "Is a good cook");
var i = 0;
$('document').ready(function(){
for (i = 0; i < allPeople.length; i++){
$("body").append("<div class='people'> " + allPeople[i].name +" </div>");
}
for (i = 0; i < allPeople.length; i++){
$("body").append("<div class='info'> " + allPeople[i].info +" </div>");
}
$('.people').hover(function(e) {
$('.info').eq($(this).index() % 4).show();
}, function(e) {
$('.info').eq($(this).index() % 4).hide();
});
});
body {
background-color: lightblue;
}
div {
background-image: url("http://themes.wdfiles.com/local--files/semi-trans/semi-transbgtransparent.png");
color: white;
padding: 2%;
margin: 2%;
border: 3px white solid;
}
.info {
display: none;
border-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
A different approach can be based on filtering the array elements (Array.prototype.filter()) in order to get the index of corresponding div.
var allPeople = [];
function win (name, info){
this.name = name;
this.info = info;
}
allPeople[0] = new win ("Shelly", "Is Cool");
allPeople[1] = new win ("Brandon", "Likes to golf");
allPeople[2] = new win ("Steve", "Plays Football");
allPeople[3] = new win ("Mia", "Is a good cook");
var i = 0;
$('document').ready(function(){
for (i = 0; i < allPeople.length; i++){
$("body").append("<div class='people'> " + allPeople[i].name +" </div>");
}
for (i = 0; i < allPeople.length; i++){
$("body").append("<div class='info'> " + allPeople[i].info +" </div>");
}
$('.people').hover(function(e) {
var txt = this.textContent.trim();
var peopleInfoIDX = 0;
allPeople.forEach(function(ele, idx) {
if (ele.name == txt)
peopleInfoIDX = idx;
});
$('.info').eq(peopleInfoIDX).show();
}, function(e) {
$('.info:visible').hide();
});
});
body {
background-color: lightblue;
}
div {
background-image: url("http://themes.wdfiles.com/local--files/semi-trans/semi-transbgtransparent.png");
color: white;
padding: 2%;
margin: 2%;
border: 3px white solid;
}
.info {
display: none;
border-color: red;
}
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
Rather than having a linear set of divs where some are people and others are info, you can nest the info with its corresponding people div so that you can target the correct info with CSS.
HTML:
<div class="people-container">
<div class="people">Shelly</div>
<div class="info">Is Cool</div>
</div>
CSS:
.people-container:hover .info {
display: block;
}
So when someone hovers over the person's name, the info can be shown.
Your easiest and non-messy solution would be to output the index onto the div using a data-index attribute.
$("body").append("<div class='people' data-index="+ i +"> " + allPeople[i].name +" </div>");
and later retrieve the data-attribute value with
console.log($(e.target).data('index'))
I'm trying to learn Javascript and at the moment and I am working on AddEventListener.
What I'm trying to do is to add a new row and so far it works.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<style>
.colorOrange {
background-color: orange;
}
.colorBlue {
background-color: blue;
}
.colorYellow {
background-color: yellow;
}
.colorGray {
background-color: gray;
}
.colorRed {
background-color: red;
}
.colorGreen {
background-color: green;
}
.colorWhite {
background-color: white;
}
#main {
margin: 0 auto;
width: 325px;
text-align: center;
background-color: gray;
}
.row {
width: 300px;
padding: 10px;
border: 1px solid black;
display: block;
}
.hideButton, .mainText, .deleteButton {
margin: 0 auto;
padding: 10px;
border: 1px solid black;
display: inline;
}
.btn {
}
</style>
</head>
<body>
<div id="main">
<div class="AddBtn btn">Add</div>
<input type="text" id="txtBox" name="text till ruta" />
</div>
<script>
var rownr = 0;
function addListeners() {
var addButton = document.getElementsByClassName('AddBtn');
for (var i = 0; i < addButton.length; i++) {
var addBtn = addButton[i];
addBtn.addEventListener('click', function () {
var elBtn = event.srcElement;
var valueBtn = elBtn.textContent;
alert(valueBtn);
hideOrShow();
addRow();
function addRow() {
switch (valueBtn) {
case "Add":
var input = document.getElementById('txtBox').value;
rownr++;
var div = document.createElement('div');
div.className = "row";
document.getElementById("main").appendChild(div);
var div2 = document.createElement('div');
div2.className = "hideButton colorGreen";
var tx = document.createTextNode("<");
div2.appendChild(tx);
div2.addEventListener('click', hideOrShow, false);
div.appendChild(div2);
var div3 = document.createElement("div");
if (input.toLowerCase() == "red") {
div3.className = "mainText colorRed";
}
else if (input.toLowerCase() == "orange") {
div3.className = "mainText colorOrange";
}
else if (input.toLowerCase() == "blue") {
div3.className = "mainText colorBlue";
}
else if (input.toLowerCase() == "yellow") {
div3.className = "mainText colorYellow";
}
else if (input.toLowerCase() == "gray") {
div3.className = "mainText colorGray";
} else {
div3.className = "mainText colorWhite";
}
tx = document.createTextNode(rownr + " " + input);
div3.appendChild(tx);
div.appendChild(div3);
var div4 = document.createElement("div");
div4.className = "deleteButton colorRed";
tx = document.createTextNode("X");
div4.appendChild(tx);
//div4.addEventListener('click', deleBtn, false);
div.appendChild(div4);
var linebreak = document.createElement("br");
div.appendChild(linebreak);
default:
}
}
So far everything works as I want it to do. But when I click on "<" it will go in to this function and find all tags with the hideButton class in it.
The first click it won't find anything, but the second time it will find the "<" value and an alert window will popup and show the value. Here is where I
get lost and can't get it to work. When you click the the third time it will
loop or whatever to call it - anyway it will show the alert window 2 times and
then if you repeat the same click it will do the same thing 3 times and so it goes.
function hideOrShow() {
var hideButton = document.getElementsByClassName('hideButton');
for (var j = 0; j < hideButton.length; j++) {
hideBtn = hideButton[j];
hideBtn.addEventListener('click', function () {
var hideElBtn = event.srcElement;
var valueHideBtn = hideElBtn.textContent;
alert(valueHideBtn);
}, false);
}
}
}, false);
}
}
window.onload = addListeners;
</script>
</body>
</html>
The goal with this exercise is that
when you click add button add the text from the input field and add that text to the new row.
and "<" shall hide the row and change it to ">" to show it again
and "X" shall just delete the row.
But what I need help with is finding the value part that I mentioned above.
Here is my rework of your javascript. I explained my solution in your comment, but it may be a bit more clear if illustrated.
In the addListeners function, I removed the hideOrShow call as it shouldn't be called in the add button.
Next, I removed the for loop in the hideOrShow method as you really are only after the caller. I also removed the addEventListener call in the same method as you already have an event listener on that element, so there's no need to add one again.
var rownr = 0;
function addListeners() {
var addButton = document.getElementsByClassName('AddBtn');
for (var i = 0; i < addButton.length; i++) {
var addBtn = addButton[i];
addBtn.addEventListener('click', function () {
var elBtn = event.srcElement;
var valueBtn = elBtn.textContent;
alert(valueBtn);
//hideOrShow();
addRow();
function addRow() {
switch (valueBtn) {
case "Add":
var input = document.getElementById('txtBox').value;
rownr++;
var div = document.createElement('div');
div.className = "row";
document.getElementById("main").appendChild(div);
var div2 = document.createElement('div');
div2.className = "hideButton colorGreen";
var tx = document.createTextNode("<");
div2.appendChild(tx);
div2.addEventListener('click', hideOrShow, false);
div.appendChild(div2);
var div3 = document.createElement("div");
if (input.toLowerCase() == "red") {
div3.className = "mainText colorRed";
}
else if (input.toLowerCase() == "orange") {
div3.className = "mainText colorOrange";
}
else if (input.toLowerCase() == "blue") {
div3.className = "mainText colorBlue";
}
else if (input.toLowerCase() == "yellow") {
div3.className = "mainText colorYellow";
}
else if (input.toLowerCase() == "gray") {
div3.className = "mainText colorGray";
} else {
div3.className = "mainText colorWhite";
}
tx = document.createTextNode(rownr + " " + input);
div3.appendChild(tx);
div.appendChild(div3);
var div4 = document.createElement("div");
div4.className = "deleteButton colorRed";
tx = document.createTextNode("X");
div4.appendChild(tx);
//div4.addEventListener('click', deleBtn, false);
div.appendChild(div4);
var linebreak = document.createElement("br");
div.appendChild(linebreak);
default:
}
}
function hideOrShow() {
var hideButton = document.getElementsByClassName('hideButton');
var hideElBtn = event.srcElement;
var valueHideBtn = hideElBtn.textContent;
alert(valueHideBtn);
}
}, false);
}
}
window.onload = addListeners;
I have a favourites feature, but want the user to be able to remove them.
This is what it looks like:
So what I want to achieve is a "Remove" link under each item which calls the remove function, and so removes that entity.
Here is my JS:
function updateFavourite(video) {
document.getElementById('favourite').onclick = function () {
if ($.grep(myfavourite, function (item) {
return item["id"] == video["id"];
}).length == 0) {
blacklist[video["id"]] = true;
myfavourite.push(video);
var html = "<li class=\"history\">" +
"<img class= \"img-rounded\" src=\"{0}\"/>" +
"<p><b title=\"{2}\"><a class=\"extendedLink\" href=\"javascript:watchFavouriteVideo(\'{1}\');\"><span></span>{2}</a></b><br>" +
"by {3}<br>" +
"{4} | {5} views</p>" +
"</li>";
$("#myfavourite").prepend(html.format(video["thumbnail"],
video["id"],
video["title"],
video["uploader"],
video["length"],
video["views"]));
}
}
}
function remove(video) {
document.getElementById('remove').onclick = function () {
myfavourite.splice(video, 1);
}
}
The problem is that it does not remove the video, and don't know how to add the "Remove" text for each entity.
Here is an example
HTML
<div id="favourites"></div>
<div id="displayList"></div>
CSS
#favourites {
width:auto;
height:100px;
}
.favourite {
width:auto;
height: auto;
margin-right:10px;
background-color:cyan;
float:left;
}
.title {
width:auto;
height: auto;
background-color:red;
border:0px;
text-align:center;
}
.picture {
width:50px;
height: 50px;
background-position:center;
display:block;
margin:0 auto;
}
.remove {
width:auto;
height: auto;
text-align:center;
}
.remove:hover {
cursor:pointer;
background-color:yellow;
}
#displayList {
min-height:20px;
clear:both;
border:1px solid black;
}
Javascript
var picsArray = [
'http://upload.wikimedia.org/wikipedia/commons/1/1b/Beys_Afroyim_with_son_%28cropped%29.jpg',
'http://upload.wikimedia.org/wikipedia/commons/8/8a/Tammam_Salam.jpg',
'http://upload.wikimedia.org/wikipedia/commons/2/27/Ratusz2007.jpg',
'http://upload.wikimedia.org/wikipedia/commons/6/60/GPN-2000-001979.jpg'
],
list = picsArray.slice(),
favourites = document.getElementById('favourites'),
displayList = document.getElementById('displayList');
function emptyNode(node) {
while (node.firstChild) {
node.removeChild(node.firstChild);
}
}
function updateDisplayList() {
emptyNode(displayList);
list.map(function (entry) {
return entry.split('/').slice(-1)[0];
}).forEach(function (shortEntry) {
var p = document.createElement('p');
p.appendChild(document.createTextNode(shortEntry));
displayList.appendChild(p);
});
}
list.forEach(function (pic) {
var favourite = document.createElement('div'),
title = document.createElement('div'),
img = document.createElement('img'),
remove = document.createElement('div');
favourite.className = 'favourite';
title.className = 'title';
img.className = 'picture';
remove.className = 'remove';
title.appendChild(document.createTextNode('Favourite'));
favourite.appendChild(title);
img.src = pic;
favourite.appendChild(img);
remove.appendChild(document.createTextNode('Remove'));
remove.addEventListener('click', function (e) {
e.target.parentNode.parentNode.removeChild(e.target.parentNode);
list = list.filter(function (ele) {
return ele !== e.target.previousSibling.src;
});
updateDisplayList();
}, false);
favourite.appendChild(remove);
favourites.appendChild(favourite);
});
updateDisplayList();
On jsFiddle