I want to create a to do list....the add and delete buttons work but i want to delete an element when i click on it...i tried with jquery but it doesnt work when i click on the javascript generated elements, but when i test on a html element that was initial on the page it works. What is the problem ? Here is the code:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap /3.3.7/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1 /jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<meta charset="utf-8">
<title></title>
</head>
<body style="margin: 40px">
<div id="div1">
<h1>To do app</h1>
<input type="text" name="" value="" id="inp">
<button type="button" name="button" onclick="adauga()">Adauga</button>
<button type="button" name="button" onclick="sterge()">Sterge</button>
<hr></hr><br>
</div>
<h5 id="xxx">jquery</h5>
<script>
function adauga() {
var cuvant = document.getElementById('inp').value;
var para = document.createElement("p");
para.setAttribute("id","z");
var node = document.createTextNode(cuvant);
para.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(para);
}
function sterge() {
var parent = document.getElementById("div1");
var child = document.getElementById("z");
parent.removeChild(child);
}
$(document).ready(function(){
$("p").click(function(){
$("p").hide();
});
});
</script>
</body>
</html>
try this one:
$(document).ready(function(){
$("body").on("click","p", function(){
$("p").hide();
});
});
Snippet:
function adauga() {
var cuvant = document.getElementById('inp').value;
var para = document.createElement("p");
para.setAttribute("id","z");
var node = document.createTextNode(cuvant);
para.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(para);
}
function sterge() {
var parent = document.getElementById("div1");
var child = document.getElementById("z");
parent.removeChild(child);
}
$(document).ready(function(){
$("body").on("click","p", function(){
$(this).hide();
});
});
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap /3.3.7/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<meta charset="utf-8">
<title></title>
</head>
<body style="margin: 40px">
<div id="div1">
<h1>To do app</h1>
<input type="text" name="" value="" id="inp">
<button type="button" name="button" onclick="adauga()">Adauga</button>
<button type="button" name="button" onclick="sterge()">Sterge</button>
<hr></hr><br>
</div>
<h5 id="xxx">jquery</h5>
</body>
</html>
The p element doesn't exist till you click the button and run the function adauga(), so you can't bind the click event to an element that doesn't exist yet, You have to bind the click event in your adauga() function as below:
function adauga() {
var cuvant = document.getElementById('inp').value;
var para = document.createElement("p");
para.setAttribute("id","z");
var node = document.createTextNode(cuvant);
para.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(para);
$("p").click(function(){
$("p").hide();
});
}
or run the function when the page is ready:
$(document).ready(function(){
adauga();
$("body").on("click","p", function(){
$("p").hide();
});
});
attention: hide() function doesn't remove an element just change the display to none, if you want to remove the element from your dom use remove() function instead!!!
When your code runs the event-listeners of the p-elements, your elements doesn't exist, so they aren't evected by the registering of the event-listener. You have to add the event-listener after you created the p element. Try something like:
var para = document.createElement("p");
$("#div1").on('click', 'p' function(){
$("p").hide();
});
Related
I made a simple "spacebar simulator" game with HTML and JavaScript. Every time the user presses spacebar an image is replaced with another one, and when the key is released it is reset to the original image.
I would like to add a counter to the page, which counts the number of times the user has pressed spacebar. The source code is below:
var myRealUrl = "./assets/spacebar.png";
$("body").on("keydown", function (e) {
if(e.which == 32){
$("#spacebar").attr("src", "./assets/spacebar_pressed.png")
}
});
$("body").keyup(function (e) {
$("#spacebar").attr("src", myRealUrl)
});
var button = document.getElementById('counter'),
count = 0;
button.onclick = function() {
count += 1;
button.innerHTML = "Click me: " + count;
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="sv">
<head>
<meta charset="utf-8">
<title></title>
<link href="https://fonts.googleapis.com/css?family=Montserrat:300,400" rel="stylesheet">
<link rel="stylesheet" href="css/stylesheet.css">
<script src="js/jquery-3.2.1.min.js"></script>
</head>
<body>
<div class="container">
<div class="title">
<h1>Spacebar Simulator 2018</h1>
<span id="counter"><p></p></span>
</div>
<img src="assets/spacebar.png" id="spacebar">
<p>Pressed</p><p id="counter">0</p><p> times.</p>
<footer>
<p>© 2018</p>
</footer>
</div>
<script src="js/spacebar.js"></script>
</body>
</html>
So set up a page level variable and increment it in the keydown event handler.
Your attempt at the "button" click code didn't work because the p element that needed to be clicked had no content inside of it, so it wasn't rendering on the screen and therefore there was nothing to click on.
Also, you can't have more than one element with the same id and it's invalid to put a p inside of a span.
var counter = 0; // Variable to hold the count
var myRealUrl = "./assets/spacebar.png";
var count = document.getElementById('counter');
$("body").on("keydown", function (e) {
if(e.which == 32){
counter++; // Increment the counter
$("#spacebar").attr("src", "./assets/spacebar_pressed.png");
count.textContent = counter; // Log the count
}
});
$("body").keyup(function (e) {
$("#spacebar").attr("src", myRealUrl)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="sv">
<head>
<meta charset="utf-8">
<title></title>
<link href="https://fonts.googleapis.com/css?family=Montserrat:300,400" rel="stylesheet">
<link rel="stylesheet" href="css/stylesheet.css">
<script src="js/jquery-3.2.1.min.js"></script>
</head>
<body>
<div class="container">
<div class="title">
<h1>Spacebar Simulator 2018</h1>
</div>
<img src="assets/spacebar.png" id="spacebar">
<p>Pressed <span id="counter">0</span> times.</p>
<footer>
<p>© 2018</p>
</footer>
</div>
<script src="js/spacebar.js"></script>
</body>
</html>
before i reinvent the wheel, i wanted to know if anyone already has written a js/jquery library that allows user to select multiple div elements by left clicking and holding the hot keys (just like in windows)
Currently i have only this much
http://jsfiddle.net/abarik/nv9hnusu/3/
<html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title> - jsFiddle demo by abarik</title>
<script type="text/javascript" src="//code.jquery.com/jquery-1.8.3.js"></script><style type="text/css"></style>
<link rel="stylesheet" type="text/css" href="/css/normalize.css">
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<style type="text/css">
.selected {
background-color:green;
}
</style>
<script type="text/javascript">//<![CDATA[
$(window).load(function(){
$('.selectable').click(function (e) {
// $('.console').append('shiftKey'+e.shiftKey)
$('.console').append('ctrlKey'+e.ctrlKey)
if (e.ctrlKey) {
$(this).toggleClass('selected');
}
});
var ids = new Array();
$('#btn').click(function () {
var selected_activities = $('.selected');
var ids = new Array();
selected_activities.each(function () {
var id_str = $(this).attr("id");
var id_arr = id_str.split("_");
var selval = id_arr[1];
if (selval != 'undefined' && selval != '' && selval != null) {
ids.push(selval);
}
});
alert(ids);
});
});//]]>
</script>
</head>
<body>
<div class="left_column">
<div class="selectable selected" id="participant_1">----1----</div>
<div class="selectable" id="participant_3">----2----</div>
<div class="selectable selected" id="participant_5">----3----</div>
</div>
<div class="right_column">
<div class="selectable" id="participant_2">----4----</div>
<div class="selectable" id="participant_4">----5----</div>
<div class="selectable" id="participant_6">----6----</div>
</div>
<input type="button" id="btn" value="Get selected ids">
<div class="console">ctrlKeyfalsectrlKeyfalsectrlKeytruectrlKeytrue</div>
</body></html>
found an library that does exactly what i need to http://evulse.github.io/finderSelect/
I'm doing a schoolproject, trying to do an list of things you need to buy.
The problem is, i can't write more than one time and add to the list, and i can't figure out why.
(It's nowhere near done.) (i have to diffrent javascript files)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<link href="main.css" type="text/css" rel="stylesheet">
<title>Inköpslista</title>
</head>
<body>
<div id="kol1" class="kol">
<h1>Inköp</h1>
<input type="image" src="img/button.png" alt="Submit" id="storknapp" onclick="klickaKnapp('skriva')"/>
<input type"text" id="skriva" placeholder="Skriv din vara här!"/>
<input type="image" id="knapp" src="pluss.png" alt="Submit"/>
</div>
<div id="kol2">
<ul id="listaavvara"></ul>
</div>
<script src="menudropdown.js" type="text/javascript"></script>
<script type="text/javascript" src="java.js"></script>
</body>
</html>
function laggtill(cool, namnVara) {
var vara = document.createElement("li");
vara.innerText = namnVara;
cool.appendChild(vara);
}
var button = document.getElementById("knapp");
button.onclick = function() {
var skriva = document.getElementById("skriva")
var namnVara = skriva.value;
if(!namnVara|| namnVara =="" || namnVara == " " ){
return false;
}
laggtill(document.getElementById("listaavvara"), namnVara);
};
javascrpit 2:
function klickaKnapp(x){
var skrivrutan = document.getElementById(x), maxH="100px";
if(skrivrutan.style.height == maxH){
skrivrutan.style.height = "0px";
} else {
skrivrutan.style.height = maxH;
}
}
HOPEFULLY YOU KNOW WHAT I MEAN! (my pictures are not here)
Because
var button = document.getElementById("knapp");
button.onclick = function() { ... }
overrides the inline event handler. You need to attach events with addEventListener
button.addEventListener("click", function(){...}, false);
Your example works for me on fiddle: http://jsfiddle.net/7zjb86ab/
So this looks like there is something wrong with your imported scripts
<script src="menudropdown.js" type="text/javascript"></script>
<script type="text/javascript" src="java.js"></script>
Are those the two files with your javascript snippets inside?
You could also try to replace
var button = document.getElementById("knapp");
button.onclick = function() {
with
function addItem() {
and then add the function as onclick attribute like you do with the klickaKnapp function
<input type="image" id="knapp" src="pluss.png" alt="Submit" onclick="addItem()" />
I have created a html webpage here:
http://diagrams.inse1d.info/wbt.html
Code:
<!DOCTYPE html>
<html>
<head>
<title>WBT Charts</title>
<link rel="stylesheet" type="text/css" href="wbt.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="wbt.js"></script>
<link href='http://fonts.googleapis.com/css?family=Ubuntu:400,500,700' rel='stylesheet' type='text/css'>
</head>
<body>
<section>
<article>
<div id="wbtBlock">
<p>Press enter to save amendments</p>
<h1>Title of wbt:<input type="text" id="wbtTitle" /></h1>
<div id="graph">
<p>Graph to go here</p>
</div>
<p><strong>Notes: </strong></p>
<p><span><input type="textarea" id="wbtNote" /></span></p>
</div>
</article>
</section>
<button>Add New WBT Chart</button>
</body>
Here is the jQuery code I wrote:
$(document).ready(function() {
$("h1").keypress(function(e) {
//get
wbtTitle = $('#wbtTitle').val();
// Write text after enter
if (e.which == 13) {
$("h1").text(wbtTitle);
}
});
$("span").keypress(function(e) {
//get
wbtNote = $('#wbtNote').val();
// Write note after enter
if (e.which == 13) {
$("span").text(wbtNote);
}
});
//Insert new WBT on button click
$("button").each(function() {
$(this).click(function() {
var wbtSet = $( "article" ).html();
$(wbtSet).insertAfter('section');
});
});
});
What I want to do is set the title and some note text using input boxes which works using jQuery. I then want to add a copy of the html into another article when the button is pressed without copying the inputs previously made with the possibility of setting new values when the article is cloned. The process should repeat over and over again.
Here is an image to help explain:
I am quite new to jQuery, I think you need to use a loop to fix this, I read that a .each() can be used http://api.jquery.com/jQuery.each/ but not quite sure.
Any help will be appreciated. Thanks.
I think I got your answer.
I changed the html a bit, because you duplicated some id's with your approach, that's not good. id's have to be unique on a page. I simply changed them to classes.
<!DOCTYPE html>
<html>
<head>
<title>WBT Charts</title>
<link rel="stylesheet" type="text/css" href="wbt.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="wbt.js"></script>
<link href='http://fonts.googleapis.com/css?family=Ubuntu:400,500,700' rel='stylesheet' type='text/css'>
</head>
<body>
<section>
<article>
<div class="wbtBlock">
<p>Press enter to save amendments</p>
<h1>Title of wbt:<input type="text" class="wbtTitle" /></h1>
<div class="graph">
<p>Graph to go here</p>
</div>
<p><strong>Notes: </strong></p>
<p><span><input type="textarea" class="wbtNote" /></span></p>
</div>
</article>
</section>
<button>Add New WBT Chart</button>
</body>
And of course the jQuery. I got rid of your first two functions because they had no purpose in this context.
$(document).ready(function() {
//Insert new WBT on button click
$("button").on('click', function() {
var title = $(this).prev().find('.wbtTitle').val();
var note = $(this).prev().find('.wbtNote').val();
var wbtSet = $(this).prev("section").html();
$(this).prev().find('.wbtTitle').replaceWith(title);
$(this).prev().find('.wbtNote').replaceWith(note);
$(this).prev("section").after('<section>' + wbtSet + '</section>');
});
});
Here is a working fiddel
Fixing the answer given by hitokun_s
window.onload = function() {
// Save a copy of the element wbtSet element on pageload
var wbtSet = $("article").clone();
$("button").each(function() {
$(this).click(function() {
// Append a new one to the holder of the wbSets
$(wbtSet).appendTo($('section'));
});
});
}
I think this is what you want to do.
window.onload = function() {
$("button").each(function() {
$(this).click(function() {
var wbtSet = $("article:first-child").clone();
wbtSet.find("input").val("");
$(wbtSet).appendTo($('section'));
});
});
}
I am a newbie in jQuery and javascript, so this might seem as a trivial question. I want to use the DOM Outliner code found here in an html page that I have created.
My html page source is as follows
<!DOCTYPE html>
<html>
<head>
<h3>Dom Outlining</h3>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script src="jquery.dom-outline-1.0.js" type="text/javascript"></script>
<script>
$(document).ready(function() {
var myExampleClickHandler = function (element) { console.log('Clicked element:', element); }
var myDomOutline = DomOutline({ onClick: myExampleClickHandler });
// Start outline:
myDomOutline.start();
// Stop outline (also stopped on escape/backspace/delete keys):
myDomOutline.stop();
});
</script>
</head>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
<div class="first class">
<p> This is a division.</p>
</div>
</body>
</html>
However, this doesn't seem to select and highlight the element as required. Can someone tell me what's missing in my code?
Because you are stoping highlighting as soon as it starts
$(document).ready(function() {
var myExampleClickHandler = function (element) { console.log('Clicked element:', element); }
var myDomOutline = DomOutline({ onClick: myExampleClickHandler });
// Start outline:
myDomOutline.start();
// Stop outline (also stopped on escape/backspace/delete keys):
//myDomOutline.stop();
});
Demo: Plunker
In ideal implementation there will be a start and stop buttons as I added in my demo.
You just need to remove myDomOutline.stop(); :)
$(document).ready(function() {
var myExampleClickHandler = function (element) { console.log('Clicked element:', element); }
var myDomOutline = DomOutline({ onClick: myExampleClickHandler });
// Start outline:
myDomOutline.start();
// Stop outline (also stopped on escape/backspace/delete keys):
// myDomOutline.stop();
});
You were starting it and then stopping it almost immediately - resulting in nothing!
Check here http://jsfiddle.net/vJYya/1/
<html>
<head>
<h3>Dom Outlining</h3>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script src="jquery.dom-outline-1.0.js" type="text/javascript"></script>
<script>
$(function() {
var myDomOutline = DomOutline({
onClick: function (element) {
console.log('Clicked element:', element);
}
});
$('#start').click(function(){
myDomOutline.start();
});
$('#stop').click(function(){
myDomOutline.stop();
});
});
</script>
</head>
<body>
<input id="start" type="button" value="Start outline"/>
<input id="stop" type="button" value="Stop outline"/>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
<div class="first class">
<p> This is a division.</p>
</div>
</body>
</html>