this.id not passing through function - javascript

I've read similar questions and tried a few different things but nothing has worked so far.
I am trying to use the id of a div, to call a variable and play a sound.
let kick = new Howl({
src: ['https://s3-us-west-2.amazonaws.com/s.cdpn.io/377560/kick.WAV']
});
$(".pad").click(function(e){
var target = e.target.id;
console.log(this.id);
target.play();
})
.pad {
position: relative;
display: inline-block;
margin: auto;
height: 40px;
width: 55px;
background: #594F4D;
box-shadow: 1px 1px 1px grey;
border-radius: 5px;
padding: 1px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/howler/2.0.12/howler.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="pad" id="kick"></div>

So what I understand from the question and code snippet is that you have a variable name same as the id of an HTML element, and you want to trigger the play method of the variable which matches the id.
A better way to keeping this information would be by using the data attribute, something like
<div class="pad" data-id="kick"></div>
But for now I am just giving a solution with id
First what you should do is keep all your instance created with new Howl into an object
let Howls = {};
Howls.kick = new Howl({
src: ['https://s3-us-west-2.amazonaws.com/s.cdpn.io/377560/kick.WAV']
});
// similarly add other sounds
Then in your click handler do this
$(".pad").click(function(e){
var target = e.target.id;
if(Howls[target]){
Howls[target].play();
}
})

Replace target.play with kick.play
let kick = new Howl({
src: ['https://s3-us-west-2.amazonaws.com/s.cdpn.io/377560/kick.WAV']
});
$(".pad").click(function(e){
var target = e.target.id;
console.log(this.id);
kick.play();
})
.pad {
position: relative;
display: inline-block;
margin: auto;
height: 40px;
width: 55px;
background: #594F4D;
box-shadow: 1px 1px 1px grey;
border-radius: 5px;
padding: 1px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/howler/2.0.12/howler.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="pad" id="kick"></div>

Use eval :
let kick = new Howl({
src: ['https://s3-us-west-2.amazonaws.com/s.cdpn.io/377560/kick.WAV']
});
$(".pad").click(function(e){
var target = e.target.id;
console.log(this.id);
eval(target).play();
})
.pad {
position: relative;
display: inline-block;
margin: auto;
height: 40px;
width: 55px;
background: #594F4D;
box-shadow: 1px 1px 1px grey;
border-radius: 5px;
padding: 1px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/howler/2.0.12/howler.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="pad" id="kick"></div>

Related

Pass HTML code as CSS content using JavaScript

I have a jQuery function like below.
function resultfucntion(state) {
if (!state.id) {
return state.text;
}
var state_output = $("<span data-tooltip='"+state.value +"'>" + state.text +
"<span>(" + state.text1 + ")</span></span>"
);
return state_output;
}
I would like to pass HTML code as content value to below CSS code
span:hover:before {
content: attr(data-tooltip);
position: absolute;
padding: 5px 10px;
margin: -3px 0 0 180px;
background: orange;
color: white;
border-radius: 3px;
}
I am getting output like below
I read this post.
Now I am looking for a JavaScript or jQuery way to pass HTML value as CSS content.
I'm not quite sure if it's possible to do it the way you want it. But this may be a solution how you could achieve the same goal:
$('span').hover(function() {
$(this).after(`<div class="tooltip-box">${$(this).attr('data-tooltip')}</div>`);
$('.tooltip-box').show();
}, function() {
$('.tooltip-box').hide();
});
.tooltip-box {
position: absolute;
padding: 5px 10px;
margin: -3px 0 0 180px;
background: orange;
color: white;
border-radius: 3px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span data-tooltip="I am <strong>strong</strong>, <em>emphasized</em> and <mark>marked</mark>.">Hyperlink</span>
Update
It is not clear to me what the point of your function should be. However, this is how you could combine the above code with your function:
function resultfucntion(state) {
if (!state.id) {
return state.text;
}
var state_output = `<span data-tooltip='${state.value}'>${state.text}<span>(${state.text1})</span></span>`;
return state_output;
}
const state = {
id: 1,
value: 'I am <strong>strong</strong>, <em>emphasized</em> and <mark>marked</mark>.',
text: 'Hyperlink',
text1: 1
}
$('body').append(resultfucntion(state));
$('span').hover(function() {
$(this).after(`<div class="tooltip-box">${$(this).attr('data-tooltip')}</div>`);
$('.tooltip-box').show();
}, function() {
$('.tooltip-box').hide();
});
.tooltip-box {
position: absolute;
padding: 5px 10px;
margin: -3px 0 0 180px;
background: orange;
color: white;
border-radius: 3px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Why can I not remove the appended elements that has a class name call building-x?

For some reason I can not remove any of the building-x elements that JavaScript generates. So I'm wondering why?
So I change my code a bit and I ended up adding building-x to the HTML to see if that will do the trick and as soon as I did that, it removed the generated HTML version of building-x but I still can not remove the generated JavaScript version of building-x.
What would I have to do to also be able to remove the JavaScript generated version of building-x?
Here is my code
document.addEventListener('DOMContentLoaded',function(){
/*<Add another building>*/
document.querySelector('#add-another-building').addEventListener('click',addAnotherBuilding);
function addAnotherBuilding(){
if(document.querySelector(".building-x")){
document.querySelector(".building-x").insertAdjacentHTML("afterend","<div class='building-x'></div>");
}
else{
document.querySelector("#first-building").insertAdjacentHTML("afterend","<div class='building-x'></div>");
}
}
/*</Add another building>*/
/*<Remove the targeted buildingX>*/
if(document.querySelector('.building-x')){
var buildingXs= document.querySelectorAll('.building-x');
for(var i=0; i < buildingXs.length; i++){
buildingXs[i].addEventListener('click',removeTheTargetedBuildingX);
}
function removeTheTargetedBuildingX(event){
var removeTheTargetedBuildingX = event.currentTarget;
removeTheTargetedBuildingX.parentNode.removeChild(removeTheTargetedBuildingX);
}
}
/*</Remove the targeted buildingX>*/
});
#buildings{
background-color: gray;
}
#first-building{
background-color: red;
height: 150px;
width: 50px;
display: inline-block;
}
#add-another-building{
margin-bottom: 25px;
display: block;
}
.building-x{
background-color: blue;
display: inline-block;
height: 100px;
width: 50px;
margin-left: 5px;
margin-right: 4px;
margin-bottom: 5px;
}
<button id='add-another-building'>Add another building</button>
<div id='buildings'>
<div id='first-building'></div><!--</first-building>-->
<div class='building-x'></div><!--</building-x>-->
</div><!--</buildings>-->
The original problem was that the part of the code that adds listeners was only run once at the beginning, when there were no building-x. Thus no js-generated building-x ever got a listener.
When you added a starting html building-x, that one got a listener but not subsequent js-generated building-x.
The solution is to call the add-listener code after adding a js-building x. In the below example, I have removed the html-starting building-x.
document.addEventListener('DOMContentLoaded',function(){
/*<Add another building>*/
document.querySelector('#add-another-building').addEventListener('click',addAnotherBuilding);
function addAnotherBuilding(){
if(document.querySelector(".building-x")){
document.querySelector(".building-x").insertAdjacentHTML("afterend","<div class='building-x'></div>");
}
else{
document.querySelector("#first-building").insertAdjacentHTML("afterend","<div class='building-x'></div>");
}
addListener();
}
/*</Add another building>*/
/*<Remove the targeted buildingX>*/
function addListener() {
var buildingXs = document.querySelectorAll('.building-x');
for(var i=0; i < buildingXs.length; i++){
if (buildingXs[i].classList.contains("listening") === false) {
buildingXs[i].addEventListener('click',removeTheTargetedBuildingX);
buildingXs[i].classList.add("listening");
}
}
}
function removeTheTargetedBuildingX(event){
var removeTheTargetedBuildingX = event.currentTarget;
removeTheTargetedBuildingX.parentNode.removeChild(removeTheTargetedBuildingX);
}
});
#buildings{
background-color: gray;
}
#first-building{
background-color: red;
height: 150px;
width: 50px;
display: inline-block;
}
#add-another-building{
margin-bottom: 25px;
display: block;
}
.building-x{
background-color: blue;
display: inline-block;
height: 100px;
width: 50px;
margin-left: 5px;
margin-right: 4px;
margin-bottom: 5px;
}
<button id='add-another-building'>Add another building</button>
<div id='buildings'>
<div id='first-building'></div><!--</first-building>-->
</div><!--</buildings>-->

CSS Doesn't Work For Submitted Input

I've decided to try and make a Notes program as a learning experience. The point was to problem-solve on my own, but I'm pretty clueless as to why this won't work.
When I Shift + Double Click a note to rename it the note changes from a <div> to <input>, but the CSS stays the same. When I press enter (which submits the input) the changes back to <div>, and the CSS is there, but it is very small and doesn't take the shape of the text. Any idea why? Thanks!
Code:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<button class="newList" onclick="newNote()">Create a new note</button>
<br></br>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>
function clickNote(){
if(event.shiftKey){
$( "div" ).click(function() {
$( this ).replaceWith( "<tr><td><form'><input class='rename' placeholder='Type here' onkeydown='enter(event)' id='newListName' autofocus>" + "</input></form></td></tr>" );
});
} else {
location.href='list.html';
}
}
function enter(event){
var enter = event.which;
if (enter == 13){
var input = document.getElementById("newListName");
$( "input" ).keyup(function() {
$( this ).replaceWith( "<tr><td><div class='list' id='list' onclick='clickNote()'>" + input.value + "</div></td></tr>" );
});
}
}
function newNote(){
var newNt = document.createElement("DIV");
var text = "Rename with Shift + Double Click"
newNt.textContent = text;
newNt.setAttribute('class', 'list');
newNt.setAttribute('id', 'list');
newNt.setAttribute("onclick", "clickNote()");
document.body.appendChild(newNt);
}
</script>
</body>
</html>
CSS:
:root {
--main-color: #FFE033;
--secondary-color: #FEC82A;
}
.newList {
height: inherit;
width: 10%;
padding: .4%;
position: relative;
border-bottom: 4px solid var(--secondary-color);
background: var(--main-color);
}
.list {
height: inherit;
width: 10%;
padding: .4%;
position: relative;
border-bottom: 4px solid var(--secondary-color);
background: var(--main-color);
}
.rename {
height: 2.5em;
width: 116%;
padding: .4%;
position: relative;
border-bottom: 4px solid var(--secondary-color);
background: var(--main-color);
}
#list {
cursor: pointer;
}
Am not sure why you are doing this, but you are adding td tr around the div which make it insde a table and create this issue as the width is defined with 10%. Remove it and it should work fine. You need also to correct the input tag.
function clickNote() {
if (event.shiftKey) {
$("div").click(function() {
$(this).replaceWith("<input class='rename' placeholder='Type here' onkeydown='enter(event)' id='newListName' autofocus>");
});
} else {
location.href = 'list.html';
}
}
function enter(event) {
var enter = event.which;
if (enter == 13) {
var input = document.getElementById("newListName");
$("input").keyup(function() {
$(this).replaceWith("<div class='list' id='list' onclick='clickNote()'>" + input.value + "</div>");
});
}
}
function newNote() {
var newNt = document.createElement("DIV");
var text = "Rename with Shift + Double Click"
newNt.textContent = text;
newNt.setAttribute('class', 'list');
newNt.setAttribute('id', 'list');
newNt.setAttribute("onclick", "clickNote()");
document.body.appendChild(newNt);
}
:root {
--main-color: #FFE033;
--secondary-color: #FEC82A;
}
.newList {
height: inherit;
width: 10%;
padding: .4%;
position: relative;
border-bottom: 4px solid var(--secondary-color);
background: var(--main-color);
}
.list {
height: inherit;
width: 10%;
padding: .4%;
position: relative;
border-bottom: 4px solid var(--secondary-color);
background: var(--main-color);
}
.rename {
height: 2.5em;
width: 100%;
padding: .4%;
position: relative;
border-bottom: 4px solid var(--secondary-color);
background: var(--main-color);
}
#list {
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="newList" onclick="newNote()">Create a new note</button>

Change picture when hovering with mouse

Good morning world! I've got another problem with my project, this time the JavaScript isn't working, I want the picture to change when I'm holding my mouse pointer over it, thanks for your patience!
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="mystyle.css" type="text/css" />
<title>Konst UF</title>
<meta charset="utf-8" />
<script type="text/javascript" language="javascript">
if (screen.width <= 699) {
document.location = "mobile.html";
}
document.getElementById("Orderbutton").onclick = function () {
location.href = "http://www.youtube.com/";
};
function billFunction() {
var Bill = getElementById("BillGate");
if (img.src.match("Bill")) {
img.src = "bill-gates.jpg";
} else {
img.src = "Card.jpg";
}
}
</script>
<body>
<p class="madeby">Made by Albin Karlsson and Oliver Jansson</p>
<center>
<ul>
<li>
<p class="Home">Home</p>
</li>
<li>
<p class="Products">Products</p>
</li>
<li>
<p class="About">About Us</p>
</li>
</ul>
</center>
<center><p class="para1">Konst UF</p></center>
<center>
<img
id="BillGate"
src="bill-gates.jpg"
alt="Bill Gates"
class="Billgates"
onmouseover="billFunction()"
/>
</center>
<marquee><h2>Bill GATES</h2></marquee>
<div></div>
<div class="sidepanels1">
<center>
<img class="Konstbild" src="Konst_uf_1.jpg" alt="Konst" />
</center>
<h2>Unknown</h2>
<p>I have no idea haha</p>
</div>
<div class="sidepanels2">
<center>
<img class="Konstbild" src="mikrofiberduk-konst.jpg" alt="Monalisa" />
</center>
<center><h2>Mona Lisa</h2></center>
<center>
<p>Mona Lisa is a painting which was painted by Leonardo Da Vinci</p>
</center>
</div>
<center>
<button
id="Orderbutton"
type="button"
onclick="location.href = 'http://www.youtube.com/';"
>
Order Our Products
</button>
</center>
</body>
</head>
</html>
That was the html code and I hope you could find the problem, if you need the css I got it too:
body {
background-color: grey;
border: grey solid 1px;
}
p.para1 {
margin: auto;
width: 40%;
border: 3px solid black;
padding: 20px;
background-color: black;
color: white;
font-size: 30px;
}
div.sidepanels1 {
border: 5px dotted green;
background-color: grey;
position: absolute;
top: 10px;
right: 10px;
width: 320px;
height: 550px;
text-align: center;
margin-top: 40px;
}
div.sidepanels2 {
border: 5px dotted green;
background-color: grey;
position: absolute;
top: 10px;
left: 10px;
width: 320px;
height: 550px;
margin-top: 40px;
}
p.iframe {
position: absolute;
top: 20px;
text-align: center;
}
div.2nd {
background-color: black;
color: white;
}
img.asus-logo {
width: 1200px;
margin-left: auto;
margin-right: auto;
border: 2px solid black;
}
img.Billgates {
margin-top: 30px;
border: 2px solid black;
margin-bottom: 40px;
}
img.Konstbild {
margin-top: 20px;
width: 300px;
height: 300px;
border: 3px solid green;
margin-right: auto;
margin-left: auto;
}
ul {
list-style-type: none;
}
p.madeby {
position: fixed;
}
Thank you !
Lets take a look at your billFunction, as there are a few problems with this function.
function billFunction() {
var Bill = getElementById('BillGate');
if (img.src.match("Bill")) {
img.src = "bill-gates.jpg";
} else {
img.src = "Card.jpg";
}
}
First of all, getting the element of your desire requires you to use document.getElementById, rather than just getElementById. Changing that should give you the correct element.
Next, you are setting img.src, but variable img is never defined. I assume this should be Bill.src instead. (Side note, I want to advise you to use lowerCamelCase variable names)
Last, your logic for checking which image to use looks wrong. Bill (capital B) can never be in bill-gates. Changing this logic using all lowercase should work.
You will get something along the lines of:
function billFunction() {
var bill = document.getElementById('BillGate');
if (bill.src.match("bill")) {
bill.src = "bill-gates.jpg";
} else {
bill.src = "Card.jpg";
}
}
In your JavaScript change this
function billFunction(img) {
var Bill = document.getElementById('BillGate');
if (img.src.match("Bill")) {
img.src = "bill-gates.jpg";
} else {
img.src = "Card.jpg";
}
}
And in your HTML
<img id="BillGate" src="screenshot_tweet.png" alt="Bill Gates" class="Billgates" onmouseover="billFunction(this)"/>
Also you should comment the onclick code before, it's causing you problems.
A better solution would be to do this only with CSS. It's much easier.
#bill {
background-image: url("bill-gates.jpg");
}
#bill:hover {
background-image: url("Card.jpg");
}
function billFunction() {
var Bill = getElementById('BillGate');
if (img.src.match("Bill")) {
img.src = "bill-gates.jpg";
} else {
img.src = "Card.jpg";
}
}
Corrected One:
$("img").hover(function(){
$(this).attr("src","bill.jpg");
},function(){
$(this).attr("src","card.jpg")
});

Should I use sessionStorage and if so, how?

I have built a simple task app that allows you to add different tasks. It works fine. I am not sure what is the best approach however to retain the data/HTML once the page is refreshed. I have heard of HTML5 session/localStorage but I am not sure if this would be the best method to use in this situation. Also, I would need help making this work if sessionStorage was a good choice.
window.onload = init;
function init() {
var generateBtn = document.getElementById("generate");
generateBtn.onclick = addTask;
var tasksWrapper = document.getElementById("tasksWrapper");
var taskDesc = document.getElementById("taskDesc");
}
var taskId = 0;
var taskBarArray = [];
function addTask() {
taskId++;
var taskBar = document.createElement("div");
var taskBarInput = document.createElement("input");
var taskBarDeleteBtn = document.createElement("input");
taskBar.setAttribute("id", taskId);
taskBar.setAttribute("class", "taskBar");
taskBarInput.setAttribute("class", "taskDesc");
taskBarInput.setAttribute("type", "text");
taskBarInput.setAttribute("placeholder", "Enter task");
function rmPlaceholder() {
taskBarInput.removeAttribute("placeholder", "Enter task");
}
function addPlaceholder() {
taskBarInput.setAttribute("placeholder", "Enter task");
}
taskBarInput.onfocus = rmPlaceholder;
taskBarInput.onblur = addPlaceholder;
taskBarInput.setAttribute("name", "taskDesc");
taskBarInput.setAttribute("value", taskDesc.value);
taskBarDeleteBtn.setAttribute("class", "deleteBtn");
taskBarDeleteBtn.setAttribute("type", "button");
taskBarDeleteBtn.setAttribute("value", "x");
var addTaskBar = tasksWrapper.appendChild(taskBar);
var targetTaskId = document.getElementById(taskId);
var addTaskBarInput = targetTaskId.appendChild(taskBarInput);
var AddTaskBarDeleteBtn = targetTaskId.appendChild(taskBarDeleteBtn);
taskBarArray.push(taskBar);
taskDesc.value = "";
taskBarDeleteBtn.onclick = removeTask;
function removeTask(e) {
taskBarDeleteBtn = e.target;
tasksWrapper.removeChild(taskBar);
taskBarArray.pop(e);
if (taskBarArray.length < 1) {
taskId = 0;
}
}
}
#main_wrapper {
margin: 0 auto;
max-width: 528px;
width: 100%;
height: 20px;
}
.taskBar {
width: 100%;
background: #333230;
border-bottom: 1px solid #fff;
border-radius: 10px;
}
.taskDesc {
margin: 10px 0 10px 10px;
background: none;
border: none;
outline: none;
font-size: 20px;
color: #fff;
text-transform: uppercase;
z-index: 9999;
}
.deleteBtn {
margin: 6px 6px 0 0;
padding: 6px;
width: 32px;
background: #8F0A09;
font-size: 15px;
color: #fff;
border-radius: 100px;
border-color: #000;
float: right;
outline: none;
}
#header {
padding: 10px;
background: #000;
border-bottom: 1px solid #fff;
border-radius: 10px;
}
#taskDesc {
padding: 2px 0;
width: 50%;
font-size: 20px;
}
#generate {
padding: 5px 83px;
background: #82CC12;
font-size: 20px;
border-color: #000;
border-radius: 5px;
outline: none;
}
::-webkit-input-placeholder {
color: #4C4B48;
}
::-moz-placeholder {
color: #4C4B48;
}
:-ms-placeholder {
color: #4C4B48;
}
<div id="main_wrapper">
<div id="header">
<input type="text" id="taskDesc"></input>
<input type="button" id="generate" value="Add task">
</div>
<div id="tasksWrapper">
</div>
</div>
Here I would use localStorage, it will be remembered even after the session has timed out. A session is probably ended if the user restarts their browser.
The only problems I see with localStorage is the 10 MB size limit on desktops (2 MB om mobile devices I think), and that it's not easy enough to get data from localStorage to the server. But localStorage would be a perfect fit for a TODO app with simple items.

Categories

Resources