How do I add a div onclick in javascript? - javascript

I am making a grocery cart list, where you can add groceries onto the website and it adds all of the prices together. But the problem is, I dont know how to add an item onclick. Here is the link to the site: https://aaryank.codewizardshq.com/GroceryCart/index.html
Here is my html:
<link href="https://fonts.googleapis.com/css?family=Bungee|Bungee+Shade|Covered+By+Your+Grace" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Open+Sans:800" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="style.css">
<div class="page" id="page">
<title> Your Grocery Cart </title>
<header>
<h1> Your Grocery Cart </h1>
</header>
<span> <u> Your Items </u> </span>
<br><br>
<div class="item" id="item">
<u><span id="itemSpan"> Item #<span id="itemNumber"></span></span></u>
<br>
</div>
<input type="text" id="itemName"><span>, $<input id="priceInput"></span>
<br><br>
<button onclick="addItem()"> + Add an Item + </button>
<br><br><br><br>
<span> <u> Total Amount ($) </u> </span>
<br><br>
<input type="text" id="outputBox" name="outputBoxName" disabled="disabled">
<br>
</div>
<script type = "text/javascript" src = "js.js"></script>
I don't have any javascript, just "function addItem(){}".

I suppose what you are looking for is how to create a new DOM element, a DIV in this case, and how to add it somewhere in the DOM, programmatically.
Generally speaking, you first create an element
// Create a new div
var new element = document.createElement("div");
// Set its content to something meaningful
element.innerHTML = "Hi I am new"
then, you need to append this new element as a child of some other element, its "container" so to say. Let's add it to that middle div which you named "page".
// Get a container for your new div
var container = document.getElementById("page");
// Add your new div to the container
container.appendChild(element);

There are two common ways to add a javascript click handler in web development.
The first way is to attach it in the HTML, via an onclick attribute:
<div id="myDiv" onclick="alert('hello, world');">Contents of Div</div>
The second way is to attach it from JavaScript. In script, you will need to have a handle on the DIV element; you can use functions like document.getElementById or document.querySelector to do this. The former takes as its parameter a string which is an element id; the latter takes a CSS-style selector.
Either of these will get a handle to the DIV above:
var myDiv = document.getElementById("myDiv");
var myDiv = document.querySelector("#myDiv");
Once you have the handle, you can use its addEventListener method trigger your function when the event is emitted.
function myFunction() {
console.log('hello, world');
}
myDiv.addEventListener("click", myFunction);

Related

Select only the text inside div of sibling with class name, having many families of same class names

I wanted to copy the texts when the copy button is clicked. But, it copies the last(3rd) paragraph text when pressing any of the three buttons. It suppose to find previous sibling and copy that text when that particular button is clicked.
Here's my code. I think, I went wrong in the sibling thing. Let me know what I did wrong here:
//finding text to copy
$(document).ready(function(){
$(document).on('click', '.phc-hashtags-box-button', function () {
$(this).closest('.phc-hashtags-box').find('.phc-hashtags-box-tags');
copy = copy +$(this).text();
});
});
function copyToClipboard(element) {
var $temp = $('<input>');
$('body').append($temp);
$temp.val($(element).text()).select();
document.execCommand('copy');
$temp.remove();
}
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div class="phc-home-hashtags">
<div class="container">
<div class="phc-hashtags-box">
<h3 class="phc-hashtags-box-title">Dog1</h3>
<p class="phc-hashtags-box-tags">#dog #dogstagram #instadog #dogsofinstagram #worldofdogs #dogslove #cutedog #doggy #igdogs #dogs #pet #dogoftheday #myfriend #doglover #ilovemydog #ilovedog #doglove #doglife #mydog #happydog #1st</p>
<button onclick="copyToClipboard('.phc-hashtags-box-tags')" class="phc-hashtags-box-button">Copy</button>
</div>
<div class="phc-hashtags-box">
<h3 class="phc-hashtags-box-title">Dog2</h3>
<p class="phc-hashtags-box-tags">#dog #dogstagram #instadog #dogsofinstagram #worldofdogs #dogslove #cutedog #doggy #igdogs #dogs #pet #dogoftheday #myfriend #doglover #ilovemydog #ilovedog #doglove #doglife #mydog #happydog #2nd</p>
<button onclick="copyToClipboard('.phc-hashtags-box-tags')" class="phc-hashtags-box-button">Copy</button>
</div>
<div class="phc-hashtags-box">
<h3 class="phc-hashtags-box-title">Dog3</h3>
<p class="phc-hashtags-box-tags">#dog #dogstagram #instadog #dogsofinstagram #worldofdogs #dogslove #cutedog #doggy #igdogs #dogs #pet #dogoftheday #myfriend #doglover #ilovemydog #ilovedog #doglove #doglife #mydog #happydog #3rd</p>
<button onclick="copyToClipboard('.phc-hashtags-box-tags')" class="phc-hashtags-box-button">Copy</button>
</div>
</div>
</div>
</body>
</html>
Instead of picking by class which gets all of the element with that class, limit your find to the parent() div of the button and it will only get the relevant text:
$(document).ready(function(){
$(document).on('click', '.phc-hashtags-box-button', function () {
$(this).parent().find('.phc-hashtags-box-tags'); // notice the change on this line.
copy = copy +$(this).text();
});
});
EDIT:
Working solution:
Now i noticed - you are not passing a single element to copyToClipboard.
<button onclick="copyToClipboard('.phc-hashtags-box-tags')" class="phc-hashtags-box-button">Copy</button>
is sending the saving to copy the last element from 3 found with this. Try instead:
<button onclick="copyToClipboard($(this).parent())" class="phc-hashtags-box-button">Copy</button>
I believe that when you pass '.phc-hashtags-box-tags' to the onclick attr of the button elements, it is matching all of the elements with that class and returning the last match for the value of your function.
Instead, try changing the button onclick handler to:
copyToClipboard($this)
That said, the execCommand function is not working in the provided snippet so verifying is difficult.
Perhaps try passing IDs or try to architect a more elegant solution. So many relative jQuery selectors will inevitably cause bugs as complexity grows.

Get html after manipulating the html content using Jquery

In my js function, I want to change the attribute of certain elements inside a div, then I need to pass the html content of that div to another function. However, the html I obtained by using html() method is not changed. How can I get the html after the change? The code is shown below:
function copyDiv() {
//set the content of the textarea
$('#text_field').val("test");
//get the content of the textarea, the content is changed
alert($('#text_field').val());
//get the html content and set it to the new div
//However, this html is not changed
$('#newDiv').html( $('#myDiv').html());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myDiv">
<label for="text_field">text: </label>
<textarea class="form-control" id="text_field"></textarea>
</div>
<div id='newDiv'>
</div>
<button type="button" onclick="copyDiv();">test</button>
I've modified your code to copy the value of the textarea to the new textarea after the HTML is duplicated, since this value isn't part of the DOM (and won't come along automatically).
I also removed the ID attribute from the textarea, since you can't have multiple elements on one page with the same ID, which your code was resulting in.
function copyDiv() {
$formControl = $('#myDiv .form-control');
//set the content of the textarea
$formControl.val("test");
//get the content of the textarea, the content is changed
alert($formControl.val());
//get the html content and set it to the new div
$('#newDiv').html( $('#myDiv').html());
$('#newDiv .form-control').val( $formControl.val() );
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myDiv">
<label for="text_field">text: </label>
<textarea class="form-control" name="text_field"></textarea>
</div>
<div id='newDiv'>
</div>
<button type="button" onclick="copyDiv();">test</button>
Use jQuery.clone() instead of .html().
Replace this
$('#newDiv').html( $('#myDiv').html());
to be this
$('#newDiv').html( $('#myDiv').clone());
You can try the following code,in case you want to set the content inside the text area you should use this code $('#text_field').text("test"); and set the inner text of the text area.
In case you want to change the value attribute you can use this code $('#text_field').attr("value","test");.The rest of the code is the same.
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Tring Reset</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myDiv">
<label for="text_field">text: </label>
<textarea class="form-control" id="text_field"></textarea>
</div>
<div id='newDiv'>
</div>
<button type="button" onclick="copyDiv();">test</button>
<script>
function copyDiv() {
//set the content of the textarea
$('#text_field').text("test");
//to set the value attribute of th text area
$('#text_field').attr("value","test");
//get the content of the textarea, the content is changed
alert($('#text_field').text());
//get the html content and set it to the new div
//However, this html is not changed
$('#newDiv').html( $('#myDiv').html());
}
</script>
</body>
</html>

Changing Background and Foreground with linked css in html

I have looked literally everywhere. The goal is to
Use the classes in the stylesheet to set color and background
For example, class selector colorA will set the text color to color ‘A’
Change the color of the text by changing the class of the div with id foreground
Change the background color by changing the class of the div with id background.
I was able to change it by manually entering the color, but when I try to change it by getting className it fails.
Here is my code Ive tried several different things with no luck, please help:
JavaScript:
function changeBG(col) {
var x = document.getElementsByTagName("DIV")[0];
x.backgroundColor = (col);
}
HTML:
<body>
<div class="holder">
<div id="background" class="backgroundC">
<div id="foreground" class="colorE">
<p>
Lorem ipsum </p>
</div>
</div>
</div>
<div class="holder">
<table>
Foreground <INPUT type="button" value="A" class = "colorA" name="button3" onClick= "document.fgColor= 'colorA'">
<INPUT type="button" value="A" class = "colorB" name="button3" onClick="document.fgColor='.colorB'">
Background <INPUT type="button" value="B" class = "backgroundA" name="button3" onClick="document.bgColor = '.backgroundA'">
<INPUT type="button" value="B" class = "backgroundB" name="button3" onClick= changeBG(document.getElementsByClassName("backgroundB"))>
</table>
</div>
CSS Stylesheet:
.colorA {
color: #4581cf;
}
.colorB {
color: #B7E2FF;
}
.backgroundA {
background-color: #4581cf;
}
.backgroundB {
background-color: #B7E2FF;
}
Try this
Make sure you are passing correct class nam
function changeBG(col) {
var x = document.getElementsByTagName("DIV")[0];
x.className=col;
}
changeBG's first parameter is wrong.
in w3c getElementsByClassName method definition
The getElementsByClassName() method returns a collection of all elements in the document with the specified class name, as a NodeList object
in html code, click event binding
onClick= changeBG(document.getElementsByClassName("backgroundB"))
in js, click event handler
x.backgroundColor=col;
col object is a collection of elements have class attribute containing 'backgroundB'.
backgroundColor is a element property, set with color value. ex) #f3f3f3
You can fix it like this.
x.className = "background" + col[0].value; //col[0] is the input element classfied 'backgroudB'. col[0].value equals 'B'
The className property sets or returns the class name of an element.
Using JQuery.
Create a new form and then copy this code and paste it, you will notice how specific div in specific class color can be changed easily.
<html>
<head>
<title>The Selecter Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$(".big, #div3").css("background-color", "yellow");
});
</script>
</head>
<body>
<div class="big" id="div1">
<p>This is first division of the DOM.</p>
</div>
<div class="medium" id="div2">
<p>This is second division of the DOM.</p>
</div>
<div class="small" id="div3">
<p>This is third division of the DOM</p>
</div>
</body>
</html>

Create element in another div element using classname

I'm trying to create new elements in another pre-existing <div> element using js DOM.
I'm able to do this if that <div> is called using id but I want to accomplish this by class
This is what I have so far
<html>
<body>
<button onclick="whiskey()">go</button>
<div class="pagination-pagination-right">
<!-- I want to spawn new Elements here !-->
</div>
<div class="controlElement">
<p> This is just a control Element</p>
</div>
<script type="text/javascript">
function whiskey(){
var input=document.createElement("input");
input.type="text";a
input.id="sad";
var newdiv=document.createElement("div");
newdiv.appendChild(input);
/* this part doesn't work */
var maindiv=document.getElementsByClassName("pagination-pagination-right");
maindiv.appendChild(newdiv);
}
</script>
</body>
</html>
getElementsByClassName() returns a HTMLCollection which is an array like collection of object, which does not have the appendChild() method. You need to get the first element form the list using an index based lookup then call the appendChild()
function whiskey() {
var input = document.createElement("input");
input.type = "text";
//ID of an element must be unique
input.id = "sad";
var newdiv = document.createElement("div");
newdiv.appendChild(input);
var maindiv = document.getElementsByClassName("pagination-pagination-right");
maindiv[0].appendChild(newdiv);
}
<button onclick="whiskey()">go</button>
<div class="pagination-pagination-right">
<!-- I want to spawn new Elements here !-->
</div>
<div class="controlElement">
<p>This is just a control Element</p>
</div>
You could also do this by using jQuery
HTML
<button>go</button>
<div class="pagination-pagination-right">
<!-- I want to spawn new Elements here !-->
</div>
<div class="controlElement">
<p> This is just a control Element</p>
</div>
jQuery
$(function(){
$('button').click(function(){
$('<div>A</div>').appendTo('.pagination-pagination-right');
});
});
You can replace $('<div>A</div>') part with whatever element you want to append in your <div>
Fiddle here

Traversing DOM from span in / out of divs

I'm adding a click event to a span that is within a div. The target of this event, which will become visible, is a first div that is within a div, two divs down. How can I traverse the DOM to find it?
Perhaps it'll be clearer with the code:
<div a>
<h2>
<span id="here">Click</span>
</h2>
</div>
<div></div>
<div>
<div class="targetDiv">This is the div we need to find</div>
<div class="targetDiv">There are other divs with the same id, but we don't need to find those</div>
<div class="targetDiv">Not looking for this one </div>
<div class="targetDiv">Or this one either</div>
</div>
I've searched left and right and cannot find an answer. It's important to restrict the event ONLY to the first div immediately after the span.
Any help would be much appreciated.
As shown, the code would look like this:
$('span#here').on('click', function() {
$(this).closest('div').siblings(':contains(.targetDiv)').children().eq(0).show();
}
Here's a sample of the fish we caught
$(function() {
$('#here').on('click', function() {
var div = $(this) //the element clicked
.closest('div') //find nearest parent div
.nextAll(':eq(1)') //find the second next div
.children(':eq(0)') //find the first child of it
.show(); //remove invisible cloak
});
});​
This works. I provided an example you can just save to a html file and test it yourself
<style>
.targetDiv{display:none;}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#here').click(function(){
$('.targetDiv').first().show(); // or whatever you want
});
});
</script>
<div a>
<h2>
<span id="here">Click</span>
</h2>
</div>
<div></div>
<div>
<div class="targetDiv">This is the div we need to find</div>
<div class="targetDiv">There are other divs with the same id, but we don't need to find those</div>
<div class="targetDiv">Not looking for this one </div>
<div class="targetDiv">Or this one either</div>
</div>

Categories

Resources