Cant manage to drag and drop picture - javascript

I am at a loss here. While the code should work, and console logs on the beginning of the drag and drop script work. after the loop in the drag and drop script they stop.
Script to fetch from mock API
$( document ).ready(function() {
const fetchData = async() => {
const response = await fetch('https://n161.tech/api/dummyapi/user?limit=5&page=1');
const data = await response.json();
// items = JSON.stringify(data);
console.log(data);
div = document.getElementById('userData');
for (var i = 0; i < data.data.length; i++) {
var str ='<div>'+data.data[i].id +' '+data.data[i].firstName +' '+ data.data[i].lastName+ '</div>';
str +='<img id ="'+data.data[i].id+'" draggable= "true" onMouseDown=(event) '+data.data[i].id +'" class="avatar" src="'+data.data[i].image+'" alt="'+data.data[i].firstName + data.data[i].lastName+'">';
div.insertAdjacentHTML( 'beforeend', str );
}
var forceStyle = document.getElementById('userData');
forceStyle.setAttribute('style', 'border:2px black; margin:10%;');
}
fetchData();
});
The drag and drop script
let pictureHolder = document.getElementById("userData");
let dropContainer = document.getElementById("left");
let avatar = document.getElementsByClassName("avatar");
let mouseOffset = {x: 0, y: 0};
let isMouseDown = false;
addAvatrListeners(avatar);
function addAvatrListeners(avatar){
console.log(avatar);
for(let i = 0; i < avatar.length; i++){
let item = avatar[i];
console.log(item);
item.addEventListener("mousedown", (e) => {
onMouseDown(e, item);
});
document.body.addEventListener("mousemove", (e)=> {
onMouseMove(e, item);
});
item.addEventListener("mouseup", (e) => {
onMouseUp(e, item);
});
}
}
function onMouseDown(e, item){
console.log('works');
isMouseDown = true;
mouseOffset = {x: item.offsetLeft - e.clientX, y: item.offsetTop - e.clientY};
item.style.backgroundColor = "aquamarine";
}
function onMouseMove(e, item){
e.preventDefault();
if(isMouseDown){
item.style.left = e.clientX + mouseOffset.x + "px";
item.style.top = e.clientY + mouseOffset.y + "px";
}
}
function onMouseUp(e, item){
isMouseDown = false;
item.style.backgroundColor = "black";
}
the html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Pictures&users</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" href="main.css">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<!-- <script scr="fetch.js"></script> -->
<script src="fetch.js"></script>
<script src="dragAndDrop.js"></script>
</head>
<body>
<div class="" id="container">
<div id="left" onMouseUp=(event) class="section"></div>
<div class="section scroll-div box right" id="userData"></div>
</div>
</body>
</html>
issues found:
drag and drop script is called first for some reason.(Probably because its asynchronous)
Events are not recognized.
Events just wont work.
offsetLeft is undefined.
I'll appreciate input, thanks in advance!

Related

How to change the loop to reverse the square print in Javascript

I'm learning java script and I'm currently working with testing in javiscritp, I've done this code that you can look at, but I don't know how to reverse now the order of these cubes to be 2 up and 1 down (see what I want in the picture) I know I need to change something for loops but I fail in any way to get what I want.
let Tabela = (function () {
const dajRed = function (tabela) {
let red = document.createElement("tr");
tabela.appendChild(red);
return red;
}
const dajCeliju = function (red, prikazi) {
let celija = document.createElement("td");
if (!prikazi) celija.style = "display:none;";
red.appendChild(celija)
return celija;
}
const crtaj = function (x, y) {
const body = document.getElementsByTagName("body")[0];
let tabelaEl = document.createElement("table");
body.appendChild(tabelaEl);
for (let i = 0; i < y; i++) {
let red = dajRed(tabelaEl);
for (let j = 0; j < x; j++) {
dajCeliju(red, j < i);
}
}
}
return {
crtaj: crtaj
}
}());
//table.crtaj(3,3)
//i=0 ⍉⍉⍉
//i=1 ⎕⍉⍉
//i=2 ⎕⎕⍉
//Tabela.crtaj(8, 8);
let assert = chai.assert;
describe('Tabela', function() {
describe('crtaj()', function() {
it('should draw 3 rows when parameter are 2,3', function() {
Tabela.crtaj(2,3);
let tabele = document.getElementsByTagName("table");
let tabela = tabele[tabele.length-1]
let redovi = tabela.getElementsByTagName("tr");
assert.equal(redovi.length, 3,"Broj redova treba biti 3");
});
it('should draw 2 columns in row 2 when parameter are 2,3', function() {
Tabela.crtaj(2,3);
let tabele = document.getElementsByTagName("table");
let tabela = tabele[tabele.length-1]
let redovi = tabela.getElementsByTagName("tr");
let kolone = redovi[2].getElementsByTagName("td");
let brojPrikazanih = 0;
for(let i=0;i<kolone.length;i++){
let stil = window.getComputedStyle(kolone[i])
if(stil.display!=='none') brojPrikazanih++;
}
assert.equal(brojPrikazanih, 2,"Broj kolona treba biti 2");
});
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Mocha Tests</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="https://unpkg.com/mocha/mocha.css" />
<style>
td{
border: 1px solid black;
height: 20px;
width: 20px;
}
</style>
</head>
<body>
<div id="ispis"></div>
<div id="mocha"></div>
<script src="https://unpkg.com/chai/chai.js"></script>
<script src="https://unpkg.com/mocha/mocha.js"></script>
<script class="mocha-init">
mocha.setup('bdd');
mocha.checkLeaks();
</script>
<script src="tabela.js"></script>
<script src="test.js"></script>
<script class="mocha-exec">
mocha.run();
</script>
</body>
</html>
Invert the check in dajCeliju:
if (prikazi) celija.style = "display:none;";
OR second option - change the params:
dajCeliju(red, j >= i);
Is this what you need?

Button for each item in localstorage

How to add button for each item in localstorage to remove that item?
I have code for setItem and getItem from localstorage, but I don't know how I can add a button or x for each item to remove it.
2020-03-01 March x
2020-04-01 April x
It looks like add item to card or remove item from card.
plz help me
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<title>jQuery UI Datepicker - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(function () {
$("#inpkey").datepicker();
});
</script>
<style>
fieldset{
margin-bottom:20px;
}
input{
padding: 7px;
height:40px;
}
</style>
</head>
<body>
<fieldset>
<input type="text" id="inpkey" placeholder="Click and select date">
<input type="text" id="inpvalue">
<button type="button" id="btninsert">Save</button>
</fieldset>
<fieldset>
<div id="output"></div>
</fieldset>
<script>
const inpkey = document.getElementById("inpkey");
const inpavv = document.getElementById("inpvalue");
const spara = document.getElementById("btninsert");
const output = document.getElementById("output");
spara.onclick = function () {
const key = inpkey.value;
const value = inpavv.value;
console.log(key);
console.log(value);
if (key && value ) {
localStorage.setItem(key, value );
location.reload();
}
};
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
const value = localStorage.getItem(key);
console.log(localStorage.getItem(key));
output.innerHTML += `${key}:&nbsp&nbsp&nbsp&nbsp ${value} <p />`;
}
</script>
</body>
</html>
Something like this: Note JSFiddle had trouble removing the last element. Might be something I overlooked in the code. Good luck.
const setup = () => {
const spara = document.querySelector('#btninsert');
const output = document.querySelector('#output');
spara.addEventListener('click', addMyEntry);
output.addEventListener('click', removeMyEntry);
insertEntries(output);
};
const insertEntries = (target) => target.insertAdjacentHTML('beforeend', loadEntryHTML());
const loadEntryHTML = () => {
let html = '';
if(localStorage.length !== 0) {
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
const value = localStorage.getItem(key);
html += createEntryHTML(key, value);
}
}
return html;
};
const createEntryHTML = (key, value) => `<p><label class="lbl_key">${key}:</label><span class="sp_value">${value}</span> remove<p/>`;
const addMyEntry = () => {
const inpkey = document.querySelector('#inpkey');
const inpavv = document.querySelector('#inpvalue');
const key = inpkey.value;
const value = inpavv.value;
if (key && value ) {
localStorage.setItem(key, value );
const output = document.querySelector('#output');
output.insertAdjacentHTML('beforeend', createEntryHTML(key, value));
}
};
const removeMyEntry = (event) => {
const target = event.target;
if(target.nodeName === 'A') {
event.currentTarget.removeChild(target.parentNode);
localStorage.removeItem(target.dataset.key);
}
};
//load
window.addEventListener('load', setup);
.lbl_key {
padding-right: 1em;
}
<fieldset>
<input type="text" id="inpkey" placeholder="Click and select date">
<input type="text" id="inpvalue">
<button type="button" id="btninsert">Save</button>
</fieldset>
<fieldset>
<div id="output"></div>
</fieldset>
A better solution to build elements dynamically.
const app = document.getElementById("app");
const localStorage = [1, 2, 3, 4];
for (let index = 0; index < localStorage.length; index++) {
// const key = localStorage.key(index);
// const value = localStorage.getItem(key);
let div = document.createElement("div");
div.className = "cart_item";
div.id = "cart_item_" + index;
div.textContent = localStorage[index] + new Date().toUTCString() + "";
let cross = document.createElement("span");
cross.className = "cross";
cross.textContent = " X";
cross.addEventListener("click", function remove() {
alert("Remove item");
});
div.appendChild(cross);
app.appendChild(div);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Static Template</title>
<link rel="stylesheet" href="app.css" />
<!-- <script src="https://deepak-proxy-server.herokuapp.com/https://gist.githubusercontent.com/deepakshrma/4b6a0a31b4582d6418ec4f76b7439781/raw/e7377474ce9e411b4d8de4b10f4437a24774c0e2/Mapper.js"></script> -->
<style>
.cart_item{
border: 1px solid;
padding: 20px 40px;
}
.cross {
color: red;
cursor: pointer;
}
</style>
</head>
<body>
<div id="app">
</div>
</body>
</html>

Only one of two practically identical JavaScript functions being run

I'm probably being very stupid here...
I have two JavaScript functions that are practically identical except each one refers to a different element.
The idea is to show and hide a toast/notification when the document loads.
For one element (errorexplanationcontainer), it works... For the other (alert), it doesn't...
CODE FOR errorexplanationcontainer (WORKS)
<div id="errorexplanationcontainer" class=""></div>
<script type="text/javascript">
window.onload = function() {
var z = document.getElementById("errorexplanationcontainer")
z.className = "show";
setTimeout(function(){ z.className = z.className.replace("show", ""); }, 3000);
}
</script>
^^ This is copied and pasted from the inspect window within Google Chrome. As you can see, the script ran successfully. We know this because class="" is absent in the source document and has been added by the script (after showing class="show" for 3 seconds).
CODE FOR alert (DOESN'T WORK)
<p id="alert">Invalid Email or password.</p>
<script type="text/javascript">
window.onload = function() {
var y = document.getElementById("alert")
y.className = "show";
setTimeout(function(){ y.className = y.className.replace("show", ""); }, 3000);
}
</script>
^^ No class="" here! The script has not worked...
FULL HTML DOC
<html class="mdl-js"><head>
<title>Dennis' Coffee Hut | CuppaDesk</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/png" href="/assets/favicon-16x16-347e46971826b54de74f354ae410242483f471bb3051a5f948d83af70770dadc.png" sizes="16x16">
<link rel="icon" type="image/png" href="/assets/favicon-32x32-ac516884b2aa2ea870ddfbd0ae383c0dd66ec1a640181174ac7adaba8e7ccd7d.png" sizes="32x32">
<link rel="apple-touch-icon" type="image/x-icon" href="/assets/apple-touch-icon-af3f73bee131a689a15fede0d2d6f7cf9698786524670279ac74cd128ec5dc40.png" sizes="180x180">
<link rel="mask-icon" type="image/x-icon" href="/assets/safari-pinned-tab-4f97411db829aebf4a4796a8f216e788ba4eeddf4d062a0a1efe473ee10fce3b.svg" color="#99cc33">
<link rel="icon" type="image/png" href="/assets/android-chrome-192x192-cb0ced957daf2743c293b898f5e595fcf07fc0842b9d0aeef37c08b8c5f74d42.png" sizes="192x192">
<link rel="manifest" href="/manifest.json">
<meta name="apple-mobile-web-app-title" content="CuppaDesk">
<meta name="application-name" content="CuppaDesk">
<meta name="msapplication-TileColor" content="#99cc33">
<meta name="msapplication-TileImage" content="/assets/mstile-144x144-5de954b6d137b31283af01b9a7645c90440392de2b44ec88949fdba65cca75e7.png">
<meta name="theme-color" content="#99cc33">
<meta name="csrf-param" content="authenticity_token">
<meta name="csrf-token" content="wphb5Z8aebicMl6E2CiCJiNPnQowqP2TVUrXOWclCukQwiX/xrbLf3jBE4YRyyswVMEaPEszTO/7xxl1/iClsw==">
<link rel="stylesheet" media="all" href="/assets/main.self-b06bcba5344c9fc9a5c6491a38f0780f4594d723339bc0543a25138d83fe3de3.css?body=1" data-turbolinks-track="reload">
<link rel="stylesheet" media="all" href="/assets/places.self-e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.css?body=1" data-turbolinks-track="reload">
<link rel="stylesheet" media="all" href="/assets/scaffolds.self-e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.css?body=1" data-turbolinks-track="reload">
<link rel="stylesheet" media="all" href="/assets/application.self-f0d704deea029cf000697e2c0181ec173a1b474645466ed843eb5ee7bb215794.css?body=1" data-turbolinks-track="reload">
<script src="/assets/rails-ujs.self-56055fe2ac3f3902deb9d12c17b2d725d432162b48fc443946daf7dfbc96d88a.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/turbolinks.self-1d1fddf91adc38ac2045c51f0a3e05ca97d07d24d15a4dcbf705009106489e69.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/action_cable.self-be3674a79bb9d13d41d259b2c17fad23aef20946dab3603b9d02374ea795005f.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/cable.self-8484513823f404ed0c0f039f75243bfdede7af7919dda65f2e66391252443ce9.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/places.self-877aef30ae1b040ab8a3aba4e3e309a11d7f2612f44dde450b5c157aa5f95c05.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/application.self-eba3cb53a585a0960ade5a8cb94253892706bb20e3f12097a13463b1f12a4528.js?body=1" data-turbolinks-track="reload"></script>
<!-- BEGIN MATERIAL DESIGN LITE -->
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<!-- <link rel="stylesheet" href="/material.min.css"> -->
<script defer="" src="https://code.getmdl.io/1.3.0/material.min.js"></script>
<!-- END MATERIAL DESIGN LITE -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<p id="alert">Invalid Email or password.</p>
<script type="text/javascript">
window.onload = function() {
var y = document.getElementById("alert")
y.className = "show";
setTimeout(function(){ y.className = y.className.replace("show", ""); }, 3000);
}
</script>
<div id="login-container">
<div id="cuppadesk-logo-large"></div>
<div id="card-white">
<h1>Log in</h1>
<div class="dropdown-dots">
<button onclick="dotsDropdown()" class="dropbtn-dots"></button>
<div id="dotsDropdown" class="dropdown-content">
<a href="/users/sign_up">
<div class="dropdown-content-item">Sign up</div>
</a>
<a href="/users/password/new">
<div class="dropdown-content-item">Forgot password</div>
</a>
<a href="/users/confirmation/new">
<div class="dropdown-content-item">Didn't recieve email confirmation</div>
</a>
<a href="/users/unlock/new">
<div class="dropdown-content-item">Didn't receive unlock instructions</div>
</a>
<a href="/users/auth/facebook">
<div class="dropdown-content-item">Log in with
Facebook
</div>
</a>
</div>
</div>
<script>
/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function dotsDropdown() {
document.getElementById("dotsDropdown").classList.toggle("show-dots");
}
// Close the dropdown menu if the user clicks outside of it
window.onclick = function(event) {
if (!event.target.matches('.dropbtn-dots')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show-dots')) {
openDropdown.classList.remove('show-dots');
}
}
}
}
</script>
<form class="new_user" id="new_user" action="/users/sign_in" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="✓"><input type="hidden" name="authenticity_token" value="wphb5Z8aebicMl6E2CiCJiNPnQowqP2TVUrXOWclCukQwiX/xrbLf3jBE4YRyyswVMEaPEszTO/7xxl1/iClsw==">
<div id="errorexplanationcontainer" class=""></div>
<script type="text/javascript">
window.onload = function() {
var z = document.getElementById("errorexplanationcontainer")
z.className = "show";
setTimeout(function(){ z.className = z.className.replace("show", ""); }, 3000);
}
</script>
<div class="field-white">
<input autofocus="autofocus" placeholder="Email" type="email" value="" name="user[email]" id="user_email">
</div>
<div class="field-white">
<input autocomplete="off" placeholder="Password" type="password" name="user[password]" id="user_password">
</div>
<div class="checkbox">
<input name="user[remember_me]" type="hidden" value="0"><input class="css-checkbox" type="checkbox" value="1" name="user[remember_me]" id="user_remember_me">
<label class="css-label clr" for="user_remember_me">Remember me</label>
</div>
<script>
// generic tools to help with the custom checkbox
function UTIL() { }
UTIL.prototype.bind_onclick = function(o, f) { // chain object onclick event to preserve prior statements (like jquery bind)
var prev = o.onclick;
if (typeof o.onclick != 'function') o.onclick = f;
else o.onclick = function() { if (prev) { prev(); } f(); };
};
UTIL.prototype.bind_onload = function(f) { // chain window onload event to preserve prior statements (like jquery bind)
var prev = window.onload;
if (typeof window.onload != 'function') window.onload = f;
else window.onload = function() { if (prev) { prev(); } f(); };
};
// generic css class style match functions similar to jquery
UTIL.prototype.trim = function(h) {
return h.replace(/^\s+|\s+$/g,'');
};
UTIL.prototype.sregex = function(n) {
return new RegExp('(?:^|\\s+)' + n + '(?:\\s+|$)');
};
UTIL.prototype.hasClass = function(o, n) {
var r = this.sregex(n);
return r.test(o.className);
};
UTIL.prototype.addClass = function(o, n) {
if (!this.hasClass(o, n))
o.className = this.trim(o.className + ' ' + n);
};
UTIL.prototype.removeClass = function(o, n) {
var r = this.sregex(n);
o.className = o.className.replace(r, '');
o.className = this.trim(o.className);
};
var U = new UTIL();
function getElementsByClassSpecial(node, classname) {
var a = [];
var re = new RegExp('(^| )'+classname+'( |$)');
var els = node.getElementsByTagName("*");
for(var i=0,j=els.length; i<j; i++)
if(re.test(els[i].className))a.push(els[i]);
return a;
}
// specific to customized checkbox
function chk_labels(obj, init) {
var objs = document.getElementsByTagName('LABEL');
for (var i = 0; i < objs.length; i++) {
if (objs[i].htmlFor == obj.id) {
if (!init) { // cycle through each label belonging to checkbox
if (!U.hasClass(objs[i], 'chk')) { // adjust class of label to checked style, set checked
if (obj.type.toLowerCase() == 'radio') {
var radGroup = objs[i].className;
var res = radGroup.split(" ");
var newRes = res[0] + " " + res[1];
var relLabels = getElementsByClassSpecial(document.body,newRes);
for (var r = 0; r < relLabels.length; r++) {
U.removeClass(relLabels[r], 'chk');
U.addClass(relLabels[r], 'clr');
}
U.removeClass(objs[i], 'clr');
U.addClass(objs[i], 'chk');
obj.checked = true;
}
else {
U.removeClass(objs[i], 'clr');
U.addClass(objs[i], 'chk');
obj.checked = true;
}
} else { // adjust class of label to unchecked style, clear checked
U.removeClass(objs[i], 'chk');
U.addClass(objs[i], 'clr');
obj.checked = false;
}
return true;
} else { // initialize on page load
if (obj.checked) { // adjust class of label to checked style
U.removeClass(objs[i], 'clr');
U.addClass(objs[i], 'chk');
} else { // adjust class of label to unchecked style
U.removeClass(objs[i], 'chk');
U.addClass(objs[i], 'clr')
}
}
}
}
}
function chk_events(init) {
var objs = document.getElementsByTagName('INPUT');
if (typeof init == 'undefined') init = false;
else init = init ? true : false;
for(var i = 0; i < objs.length; i++) {
if (objs[i].type.toLowerCase() == 'checkbox' || objs[i].type.toLowerCase() == 'radio' ) {
if (!init) {
U.bind_onclick(objs[i], function() {
chk_labels(this, init); // bind checkbox click event handler
});
}
else chk_labels(objs[i], init); // initialize state of checkbox onload
}
}
}
U.bind_onload(function() { // bind window onload event
chk_events(false); // bind click event handler to all checkboxes
chk_events(true); // initialize
});
</script>
<div class="green-submit">
<input type="submit" name="commit" value="Log in" data-disable-with="Log in">
</div>
</form>
</div>
</div>
</body></html>
Again, I'm probably missing something obvious here... I'm completely new to developing and JavaScript is something I particularly struggle with. I've read through many resources but in my mind, the code still looks correct...
Obviously, I'm wrong... So any help will be greatly appreciated!
Use window.addEventListener instead of overwriting window.onload.
For errorexplanationcontainer,
<div id="errorexplanationcontainer" class=""></div>
<script type="text/javascript">
window.addEventListener("load", function() {
var z = document.getElementById("errorexplanationcontainer");
z.className = "show";
setTimeout(function() {
z.className = z.className.replace("show", "");
}, 3000);
}, false);
</script>
For alert,
<p id="alert">Invalid Email or password.</p>
<script type="text/javascript">
window.addEventListener("load", function() {
var y = document.getElementById("alert")
y.className = "show";
setTimeout(function() {
y.className = y.className.replace("show", "");
}, 3000);
}, false);
</script>

Websockets draggable instead of onclick

I'm making a simple to-do list with WebSockets. The simple-todo is created but I only managed to create it with a click instead of the draggable option it should have. I changed the click to draggable but it didn't work. here is the code I used.
<!doctype html>
<html>
<head>
<title>Simple Todo</title>
</head>
<body>
TODO <input type="text" id="newTodoItem">
<ul id="itemsTodo">
</ul>
PROGRESS
<ul id="itemsProgress">
</ul>
DONE
<ul id="itemsDone">
</ul>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect();
/* statusses
0: todo
1: progress
2: done
*/
window.addEventListener('DOMContentLoaded', function () {
socket.emit("submitNewTodoItemMessage", {});
}, false);
// Checks if a new toto item is submitted
document.onkeyup = function (e) {
if (e.which === 13) {
var newTodoItem = {};
newTodoItem.id = parseFloat(new Date().getTime() + Math.random());
newTodoItem.status = 0;
newTodoItem.action = document.getElementById("newTodoItem").value;
if (newTodoItem !== '') {
socket.emit("submitNewTodoItemMessage", newTodoItem);
}
document.getElementById("newTodoItem").value = "";
}
};
socket.on("listOfAllTodoItemsMessage", function (listOfAllTodoItems) {
var itemsTodo = [], itemsProgress = [], itemsDone = [];
for (var i = 0; i < listOfAllTodoItems.length; i++) {
var item = listOfAllTodoItems[i];
var dragItem = "<li>" + item.action + " <span class='changeStatus' id='p_" + item.id + "'>^</span> <span class='changeStatus' id='n_" + item.id + "'>v</span></li>";
if (listOfAllTodoItems[i].status === 0) {
itemsTodo.push(dragItem);
} else if (listOfAllTodoItems[i].status === 1) {
itemsProgress.push(dragItem);
} else if (listOfAllTodoItems[i].status === 2) {
itemsDone.push(dragItem);
}
document.getElementById('itemsTodo').innerHTML = itemsTodo.join("");
document.getElementById('itemsProgress').innerHTML = itemsProgress.join("");
document.getElementById('itemsDone').innerHTML = itemsDone.join("");
}
$(".changeStatus").draggable(function (e) {
socket.emit("submitStatusUpdateTodoItemMessage", e.target.id);
});
$(".changeStatus").css('cursor', 'pointer');
});
</script>
</body>
</html>
the code snippet is now on the draggable state but it isn't working. I'm using jquery so the draggable function should work I guess.

backup streaming with jwplayer

I use this js to create a jwplayer.
<script language="javascript" type="text/javascript" src="embed/swfobject.js"></script>
<div id="playerContainer">player should load here</div>
<script language="javascript" type="text/javascript">
var flashvars = {};
flashvars.linkfromdisplay = "true";
flashvars.autostart = "true";
flashvars.height = "480";
flashvars.width = "640";
flashvars.volume = "90";
flashvars.repeat = "false";
flashvars.displayheight = "640";
flashvars.displaywidth = "480";
flashvars.skin = "embed/minimal.zip";
flashvars.stretching = "exactfit";
flashvars.file = "http://" +
escape("1.1.1.1/stream.php");
var params = {};
params.menu = "true";
params.allowscriptaccess = "always";
params.allowfullscreen = "true";
params.wmode = "transparent";
var attributes = {};
attributes.id = "playerContainer";
attributes.wmode = "transparent";
attributes.name = "playerContainer";
swfobject.embedSWF("jwplayer/player.swf",
"playerContainer", "640", "480", "8","expressInstall.swf", flashvars,
params, attributes);
</script>
This works fine but when there is any problem and the stream is down or not found, I want to stream another link.
You can use onError() to do this.
Here is a demo:
http://support.jwplayer.com/customer/portal/articles/1442607-example-a-custom-error-message
Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Displaying a Custom Error Message</title>
<link rel="icon" type="image/x-icon" href="http://www.jwplayer.com/wp-content/themes/jwplayer-105/favicon.ico">
<script type='text/javascript' src='http://p.jwpcdn.com/6/8/jwplayer.js'></script>
<style type="text/css">
body {
margin: 0; padding: 0
}
</style>
</head>
<body>
<div id="container"></div>
<script>
jwplayer("container").setup({
file: "rtmp://fms.12E5.edgecastcdn.net/0012E5/videos/Qvxp3Jnv-68183.flv",
//file: "rtmp://fml.12E5.edgecastcdn.net/3012E5/tuxcast",
image: "http://s.jwpcdn.com/thumbs/RxiqSWej-640.jpg"
});
jwplayer().onError(function(){
jwplayer().load({file:"http://content.jwplatform.com/videos/7RtXk3vl-52qL9xLP.mp4",image:"http://content.jwplatform.com/thumbs/7RtXk3vl-480.jpg"});
jwplayer().play();
});
jwplayer().onComplete(function(){
window.location = window.location.href;
});
jwplayer().onBuffer(function(){
theTimeout = setTimeout(function(){
jwplayer().load({file:"http://content.jwplatform.com/videos/7RtXk3vl-52qL9xLP.mp4",image:"http://content.jwplatform.com/thumbs/7RtXk3vl-480.jpg"});
jwplayer().play();
},5000);
});
jwplayer().onPlay(function(){
clearTimeout(theTimeout);
});
</script>
</body>
</html>

Categories