inserting divs with javascript - javascript

i have the following code that i was hoping would allow me to click a button and add another box to the page but inj stread it just resets the page every time i click one of the buttons
<style>
div.box
{
width: 50px;
height: 50px;
background-image: url("Images/smallBox.jpg");
}
div.largeBox
{
width: 100px;
height: 100px;
background-image: url("Images/largeBox.jpg");
}
</style>
<script type="text/javascript">
$(function () {
setupDragging();
});
function setupDragging() {
$(".box").draggable({ snap: true });
$(".largeBox").draggable({ snap: true });
}
function addSmallBox() {
var boxArea = document.getElementById('boxArea');
var newBox = document.createElement('div');
newBox.setAttribute('class', 'box');
boxArea.appendChild(newBox);
setupDragging();
}
function addLargeBox() {
var boxArea = document.getElementById('boxArea');
var newBox = document.createElement('div');
newBox.setAttribute('class', 'largeBox');
boxArea.appendChild(newBox);
setupDragging();
}
</script>
<form>
<button onclick="addSmallBox();">small box</button>
<button onclick="addLargeBox();">large box</button>
</form>
<div id="boxArea">
</div>
please can somebody let me know what i am doing wrong and how i can achieve what i want.
ANSWER:
just an update on the final result
<style>
div.box
{
width: 50px;
height: 50px;
background-image: url("../Images/smallBox.jpg");
position: absolute;
}
div.largeBox
{
width: 100px;
height: 100px;
background-image: url("../Images/largeBox.jpg");
position: absolute;
}
</style>
<script type="text/javascript">
$(function () {
setupDragging();
$('.addBox').click(function(e){
if($(this).hasClass('smallBox')) addSmallBox();
else if($(this).hasClass('largeBox')) addLargeBox();
e.preventDefault();
})
});
function setupDragging() {
$(".box").draggable({ snap: true });
$(".largeBox").draggable({ snap: true });
}
function addSmallBox() {
$('<div>', { class: 'box' }).appendTo('#boxArea')
setupDragging();
}
function addLargeBox() {
$('<div>', { class: 'largeBox' }).appendTo('#boxArea')
setupDragging();
}
</script>
<form>
<button class='addBox smallBox'>small box</button>
<button class='addBox largeBox'>large box</button>
</form>
<div id="boxArea">
</div>
i made use of several of the answers below and this was the final result but went down the html5 route in the end.

First of all, since you are using jQuery, if I were you, I would not use the onclick attribute in your button. Instead, add an event listener like so:
$('button').click(function(){
addLargeBox();
return false;
});
OR
$('button').click(function(e){
addLargeBox();
e.preventDefault();
});
Both of which will prevent the user's browser from following the link but will execute the JavaScript as you want.
Also, since you require two different functions to be executed depending on which button is clicked, you should probably add a class or id to differentiate the two.
Your markup would then look like this:
<button class="add-box">small box</button>
<button class="add-box large-box">large box</button>
And your JavaScript would be:
$('.add-box').click(function(){
if ($(this).hasClass('large-box')) addLargeBox();
else addSmallBox();
return false;
});

The button tag you are using is a HTML5 version of a form submit button which causes a page refresh.
Change the buttons to:
<input type="button" onclick="addSmallBox();" value="small box" />
Or put return false at the bottom of each of your javascript functions.

Couple of things:
Always separate JS from code (that means lose the onclick attributes and bind them in javascript instead.)
The form is still being submitted; have your functions return false/preventDefault (jQuery) to avoid this.
Some hints:
Since you're already using jQuery, why not build html elements with it? ($('<div>',{class:'box'}).appendTo('#boxArea') for instance)

You have to return false from the click event to prevent the default browser behavior of following the link.

I'm not sure why just by glancing at the code, but perhaps you could try retrieving the boxArea.InnerHTML, appending the appropriate HTML string to it, and setting the boxArea.InnerHTML to the result.
Something like:
boxArea.InnerHTML = boxArea.InnerHTML + "<div class='largeBox'></div>";

Related

How to get event target/this without putting the event listener in the HTML tag? [duplicate]

This question already has answers here:
Get clicked element using jQuery on event?
(6 answers)
Closed 5 years ago.
I'm not a big fan of putting my event listeners (specifically onclick in this case) in the HTML, mostly because I can't use
$(document).ready(function(){})
I would much rather define the buttons' onclick as I've commented it in the startup function. However, this doesn't refer to the clicked button when I put the listener in the script (I'm guessing because it doesn't "know" which button I clicked). I've tried setting event as a parameter to the showImage function, and finding the e.target inside it, but this didn't work either. Is there a way I can refer to the clicked button without having the onclick inside the HTML tag?
//$(document).ready(function() {
window.onload = startup;
function startup() {
$("img").hide();
//$("button").click(showImage(this));
}
function showImage(e) {
var chosen = e.value;
$('#' + chosen).fadeIn(500);
$('img:not(#' + chosen + ')').hide();
}
//});
body {background-color: #EFEFEF;}
#content {width: 80%; margin: auto; background-color: white; padding: 15px; font-family: "Century Gothic",sans-serif;}
img {height: 250px; border: solid 1px black;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<img id="pig" src="http://www.igjerstad.no/sites/default/files/styles/nodeimage/public/field/image/gris-750-5.jpg?itok=TJa-iUVg">
<img id="cow" src="https://www.matmerk.no/cms/images/3675/1200/1200/ku-nyt-norge.jpeg">
<img id="sheep" src="https://media.timeout.com/images/103778879/630/472/image.jpg">
<img id="hen" src="http://africahitz.com/wp-content/uploads/2017/01/hen-white-and-black-color.jpg">
<br>
<button value="pig" onclick="showImage(this)">Gris</button>
<button value="cow" onclick="showImage(this)">Ku</button>
<button value="sheep" onclick="showImage(this)">Sau</button>
<button value="hen" onclick="showImage(this)">Høne</button>
Thanks in advance!
PS. I would guess someone else has had this problem and maybe asked about it here. I did check if I could find a similar question on the site, but found nothing. However, I have failed to find that before, so I'm sorry if this is a duplicate.
PS2. The images in my code are not mine, nor do I have the rights for them. Please don't sue me ':D
PS3(!!). I'm not an experienced programmer, my terminology might be wrong some places. Feel free to correct me :)
Firstly you need to define function() in a click function so it should look like this:
$("button").click(function() {
//code to execute here
});
Instead of this:
$("button").click(//code to execute here);
When calling this in a button it will refer to the button and if I understand your code right, the image is hidden therefore if that is the button then you can't click a hidden image, if you're using a separate button to hide the image then in the click function you need to have e stated as the image element.
To use this you also need to call it as $(this) not just this.
This should work.
//$(document).ready(function() {
window.onload = startup();
function startup() {
console.log("window loaded");
$("img").hide();
$("button").click(function() {showImage(this)});
}
function showImage(e) {
console.log("onside eras");
var chosen = e.value;
$('#' + chosen).fadeIn(500);
$('img:not(#' + chosen + ')').hide();
}
//});
this will be set inside the event handler as event.currentTarget Ref. If you are using jQuery you can make a jQuery object from it by doing $(this). So to get the value you can do:
var chosen = $(this).prop('value');
I have also added a class myclass to the buttons to select it using $('.myclass') so that this can be seperated from other possible buttons in the page. You can also do $('button') instead to select all buttons irrespective of the class.
UPDATE
Just saw your commented out code:
$("button").click(showImage(this)); // When a button is clicked
// call the function returned by showImage(this).. err it doesnt return
// a function so it fails.
you should pass a function reference or simply a function name to the click event registration. like .click(showImage) without any function call (). In your code it will execute showImage(this) and bind the returned value to the event listener, which will apparently fail.
It should actually be:
$("button").click(showImage); // when a button is clicked
// call the function showImage with this=<clicked button> and param=event
and this will be automatically set inside the function as event.currentTarget
$(document).ready(function() {
window.onload = startup;
function startup() {
$("img").hide();
//$("button").click(showImage(this));
}
function showImage(e) {
var chosen = $(this).prop('value');
$('#' + chosen).fadeIn(500);
$('img:not(#' + chosen + ')').hide();
}
$('.myclass').on('click', showImage);
});
body {background-color: #EFEFEF;}
#content {width: 80%; margin: auto; background-color: white; padding: 15px; font-family: "Century Gothic",sans-serif;}
img {height: 250px; border: solid 1px black;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<img id="pig" src="http://www.igjerstad.no/sites/default/files/styles/nodeimage/public/field/image/gris-750-5.jpg?itok=TJa-iUVg">
<img id="cow" src="https://www.matmerk.no/cms/images/3675/1200/1200/ku-nyt-norge.jpeg">
<img id="sheep" src="https://media.timeout.com/images/103778879/630/472/image.jpg">
<img id="hen" src="http://africahitz.com/wp-content/uploads/2017/01/hen-white-and-black-color.jpg">
<br>
<button value="pig" class="myclass">Gris</button>
<button value="cow" class="myclass">Ku</button>
<button value="sheep" class="myclass">Sau</button>
<button value="hen" class="myclass">Høne</button>

How to disable Finish button after first click

I've tried the various methods that normally work, but it seems SmartWizard is preventing these methods from working.
I need to disable the Finish button and change the text after it is clicked to prevent multiple submissions. No matter where I place the code, the screen does not change, the value of the button does not change, and the button does not disable.
I tried the typical click function...
$(".actionBar .buttonFinish").click(function(){
$(".actionBar .buttonFinish").addClass("buttonDisabled");
$(".actionBar .buttonFinish").text("Sending...");
});
I also tried using this as part of the final step validation and in the FinishCallback right before the ajax call. Nothing changes until AFTER the ajax call is completed and the ajax success runs.
UPDATE
Ok, this is for sure a timing issue. If I cause the ajax call to fail, the button disables and the text changes. I need to make sure these two things occur before moving on to the ajax call. So far, I tried this but it did not work:
$(".actionBar .buttonFinish").addClass("buttonDisabled").text("Sending...").ajax({
$(".actionBar .buttonFinish").click(function(){
$(".actionBar .buttonFinish").attr('disabled', 'disabled');
$(".actionBar .buttonFinish").text("Sending...");
});
you can add this at the end of the 'onclick' event to disable the button
$(this).prop( "disabled", true );
OR
$(this).attr("disabled", 'disabled');
you need to use the function 'prop' or 'attr' depending on the jquery version
Try this.
$(document).ready(function(){
$(function(){
$(".buttonFinish").on("click", function(){
$(this).prop('disabled', true);
$(this).val("Sending...");
});
});
});
input{
display: block
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<div>
<form>
<input type="text">
<input type="text">
<input class="buttonFinish" type="submit">
</form>
</div>
UPDATE
Let me see if I understood you, you want to disable the button and the text before ajax call? You've tried with beforeSend?
$(document).ready(function(){
$(function(){
$("form").submit(function(e){
e.preventDefault();
$.ajax({
beforeSend: function(){
$(".buttonFinish").prop('disabled', true);
$(".buttonFinish").val("Sending...");
},
complete: function(){
// remove disabled and change the text
},
});
});
});
});
input{
display: block
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<div>
<form>
<input type="text">
<input type="text">
<input class="buttonFinish" type="submit">
</form>
</div>
Since your .buttonFinish is a link, not actually a button, you can't disable it with .prop('disabled', true) — you may want to use a "blocking pane" instead.
Put a div at the very end of your page, I prefer just before the </body> tag, that contains nothing and is unseen, off the page and with no height and width.
<div id="blocker"></div>
</body>
When the "button" is clicked then add a class on it that will make it show, using the full height/width of the page and with a high z-index so it is "in front" of everything else; it will get all the clicks which won't pass through to the controls underneath it as a lower z-index.
Your click handler would include $('blocker').addClass('blocking'); giving the resulting DOM ...
<div id="blocker" class="blocking"></div>
</body>
Use CSS to style #blocker so it is unseen, then style #blocker.blocking so it blocks the rest of the page.
$('a.finished').click(function(e) {
e.preventDefault();
$('#blocker').addClass('blocking');
// when ajax call finishes,
// use $('#blocker').removeClass('blocking');
});
#blocker {
position: fixed;
top: -10px;
left: -10px;
height: 0;
width: 0;
z-index: -20;
background-color: white;
}
#blocker.blocking {
height: auto;
width: auto;
bottom: -10px;
right: -10px;
opacity: 0.6;
z-index: 9000;
}
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.js"></script>
<div class="stuff">
<p>This is stuff</p>
<p>This is other stuff</p>
<p>A link is in here.</p>
</div>
<div id="blocker"></div>
Try this
<input type='button' id='btn' onclick='click_me()' value='click'>
var disable = false;
function click_me()
{
if(disable = 'false') {
$(".actionBar .buttonFinish").addClass("buttonDisabled");
$(".actionBar .buttonFinish").text("Sending...");
disable = true;
}
}

javascript - one image,two actions

I am looking for javascript command that would do the following:
Click on image -> open spoiler
Click on image again -> hide spoiler
Here is what I got so far:
javascript in my html
<script>
function myFunction() {
document.getElementById("prvy").innerHTML = document.getElementById('spoiler_id').style.display='';}
</script>
Spoiler
<a id="show_id"
onclick="document.getElementById('spoiler_id').style.display=''; document.getElementById('show_id').style.display='none';"
class="link"></a><span id="spoiler_id"
style="display: none">[Show]<button onclick="document.getElementById('spoiler_id').style.display='none';
document.getElementById('show_id').style.display='';"
class="link">[Hide]</button>
<br><h1 id="bz">Heading</h1><br><br><p>text</p></span>
And my button:
<div id="prvy" onclick="myFunction()"></div>
What I managed to do, is to click on a image, wich will open spoiler. Hovewer, I've been unable to do the second part, onclick again it will close the spoiler.
I also did serach for solution alredy, nothing worked for me, not even this: Link
I also tired if{} else{} statement but didn't work for me either.
Help would be really appreciated, as I am getting desperate on this one.
You can use jQuery .toggle() to toggle show/hide
$("#prvy").click(function() {
$("#spoiler_id").toggle();
});
Note : You need to include jQuery in your document as
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Working snippet :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="show_id"
onclick="document.getElementById('spoiler_id').style.display=''; document.getElementById('show_id').style.display='none';"
class="link"></a><span id="spoiler_id"
style="display: none">[Show]<button onclick="document.getElementById('spoiler_id').style.display='none';
document.getElementById('show_id').style.display='';"
class="link">[Hide]</button>
<br><h1 id="bz">Heading</h1><br><br><p>text</p></span>
<div id="prvy" onclick="myFunction()">button</div>
<script>
$("#prvy").click(function() {
$("#spoiler_id").toggle();
});
</script>
In the JavaScript where you click the button use the simple jQuery function toggle.
$('#spoiler_id').toggle();
Toggle will hide the element selected if it is currently shown or display the element if it is currently hidden.
you would need some state that flips when the function is called.
like this.
<script>
var state = false;
function myFunction() {
state = !state;
if(state){
//do something
}else{
//do something else
}
}
</script>
Is that all of your code, it would be easier for you and less confusing too if you just gave the buttons an on click function and then called that function in your js.
Can I see all of your html
I am giving an example to concerned question using javascript.
HTML:
<script type="text/javascript">
var permit = 'true';
function showhide() {
var getcont = document.getElementsByClassName('hidshowcont');
if (permit === 'true') {
permit = 'false';
getcont[0].style.display = 'block';
}
else {
permit = 'true';
getcont[0].style.display = 'none';
}
}
</script>
<style type="text/css">
.hidshowcont{
height: 200px;
width: 300px;
border: 1px solid #333333;
display: none;
}
</style>
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR1cSDTn18ufwjuMihttTvCPJOnFY-4hxbPcaOVd87nSPaQakbP9IERaQ" />
<br />
<br />
<div class="hidshowcont">
This is an example of hide and show the container by clicking of an image.
</div>
This will help u much

Javascript Background Change Colour

I am trying to learn Javascript on my own. So I gave myself a task: Create a button and with that button I can change the background colour. This is what I have done so far. I assume I don't need to run it under localhost like how we usually do PHP? I only drag the file to Google Chrome. So far, after clicking, it doesnt change colour at all. I also wonder why. Would be grateful if someone could point out my error
exe1.html
<html>
<head>
<link rel="stylesheet" href="layout.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.button').click(function(){
$('body').css('background', '#' + changeColour());
});
});
function changeColour() {
return Math.floor(Math.random()*16777215).toString(16);
}
</script>
</head>
<body>
<div class="buttonClickMe">
<button type="button" onclick="changeColour">Click me</button>
</div>
</body>
layout.css
button
{
background-color: red;
width: 100px;
height: 100px;
}
body
{
text-align: center;
background-color: blue;
}
Looks like you are trying to implement the click event in two ways:
as a HTML attribute
<button type="button" onclick="changeColour">
In order for this way to work, you should use changeColour as a function:
<button type="button" onclick="changeColour()">
via JS
$('.button').click(function(){ ...
This is the wrong selector for button (the . looks for elements by class name). Instead, use button:
$('button').click(function(){ ...
Either method will work and you only need one.
This should work
$(document).ready(function () {
$('.button').click(function () {
changeColour();
});
});
function changeColour() {
var col = Math.floor(Math.random() * 16777215).toString(16);
$('body').css('background', '#' + col);
}
If you are learning javascript don't jump so fast to jQuery, first do it in plain javascript, like this.
Pure JS
var array = ['black','red','yellow']; //create an array with colors
function changes(){ //create the function
document.bgColor= array[Math.floor(Math.random()* array.length)]; //change the document. for example
}
HTML
<button type="button" onclick="change()">Click me</button>
The selector you're using for the click event does not exist. Add a class to the button for it t work.
Try this:
HTML
<button type="button" class="button">Click me</button>
CSS
$(document).ready(function(){
$('.button').on('click', function(){
$('body').css('background', '#' + changeColour());
});
});
function changeColour() {
return Math.floor(Math.random()*16777215).toString(16);
}
What you've done is fine,
You should move the button class .button onto the actual button element and remove the onclick and then should work.
Here:
http://jsfiddle.net/745ex5zc/
$('.button').click(function(){...
is referring to a click on a button with the CLASS button.
Simply add class=""button" to your button and it would work, though I'd recommend using id="myId" and using $('#myId').click(function(){ instead.
Give this a try...
JSFiddle https://jsfiddle.net/w6tjtaqy/
<script>
$(document).ready(function(){
$('.button').click(function(){
$('body').css('background', '#' + changeColour());
});
});
function changeColour() {
return Math.floor(Math.random()*16777215).toString(16);
}
</script>
<style>
button
{
background-color: red;
width: 100px;
height: 100px;
}
body
{
text-align: center;
background-color: blue;
}
</style>
<div class="buttonClickMe">
<button type="button" class="button">Click me</button>
</div>

How to onclick outside an input element which is inside a div?

It maybe easy but i can't think anything to find the way when i click outside the textbox to alert something in javascript BUT when i click inside the text nothing to happen.The input text is inside the div element.
So,let's assume that my html is like bellow:
<div id="myone" onclick="javascript: myfunc();">
<input type="text" id="myInput"></input>
</div>
function myfunc()
{
alert('ok');
}
How to change that?
Thank you a lot!
Do this:
var div = document.getElementById('myone');
var funct = function(){
var input = div.querySelector("#myInput");
return false;
};
div.onclick = funct;
You shoud use this condition. e.target !== this
It is often useful to compare event.target to this in order to determine if the event is being handled due to event bubbling. This property is very useful in event delegation, when events bubble.
Use it inside your click function like this and see it in action:
$('.divover').on('click', function(e) {
if (e.target !== this) return;
thefunc();
});
var thefunc = function myfunc() {
alert('ok');
}
.divover {
padding: 20px;
background: yellow;
}
span {
background: blue;
color: white;
padding: 8px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='divover'>somelabel:
<span><input type="text" class="as" name="forename"></span>
</div>
This will work, if you do this carefully.
<div id="myone" onclick="javascript: myfunc();">
//your stuff in the clickable division.
</div>
<div style="position:absolute;">
<!--Adjust this division in such a way that, it comes inside your clickable division--><input
type="text" id="myInput"></input>
</div>
//Your script function/code here
function myfunc()
{
alert('ok');
}

Categories