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

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');
}

Related

How to select 'this' onclick?

By triggering an onClick event I would like to select the same element the onClick event is attached to, to add a class to that same element. What I tried is the following:
<div class="class1" onClick="TestFunction();">Click</div>
<script>
function TestFunction() {
$(this).addClass('active');
}
</script>
After clicking the div, the class "active" should be added to the same element, resulting in...
<div class="class1 active" onClick="TestFunction();">Click</div>
However this doesn't work. I am wondering whether the this selector works differently in this case.
The structure of the div element should stay the same and also the function should stay in the same place as it is on the onClick attribute.
The reason is this refers to the global Window object inside the function.
You have to pass this to the function so that you can refer that inside the function:
.active{
color:green;
font-size: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="class1" onClick="TestFunction(this);">Click</div>
<script>
function TestFunction(el) {
console.log(this.constructor.name) //Window
$(el).addClass('active');
}
</script>
Though it is better to avoid inline event handler:
$('.class1').click(function(){
$(this).addClass('active');
});
.active{
color:green;
font-size: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="class1">Click</div>
When using an inline handler the function invoked runs under the scope of the window element, not the element which raised the event. To work around that you can pass this as an argument:
<div class="class1" onClick="TestFunction(this);">Click</div>
function TestFunction(el) {
el.addClass('active');
}
However this is not good practice. Inline event attributes are outdated and now considered bad practice. The better way to achieve this is to attach unobtrusive event handlers. In plain JS it would look like this:
<div class="class1">Click</div>
document.querySelectorAll('.class1').forEach(el => {
el.addEventListener('click', function() {
this.classList.add('active');
});
});
In jQuery it would look like this:
<div class="class1">Click</div>
jQuery($ => {
$('.class1').on('click', function() {
$(this).addClass('active');
});
});

Text input and output it on page

I was wondering if I can create a text input where users can type some text and then immediately display them on page, same as twitter. I know about alert window or prompt window but I need something different, a text input on website.
Hope it can be done in JavaScript.
Use .keyup() for the input field then replace the content of the output div.
$(".div-input").keyup(function() {
$(".output").html($(this).val());
});
.output {
margin-top: 20px;
font-size: 2em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="div-input" />
<div class="output">
</div>
If you want to display the input on submit, you could attach a .submit() event on a form tag then use appendTo on the div if you want to insert multiple elements;
$(".form-input").submit(function(e) {
e.preventDefault();
var value = $(".div-input").val();
$("<div class='outputs'>" + value + "</div>").appendTo($(".output"));
});
.output {
margin-top: 20px;
}
.outputs {
padding: 20px;
font-size: 2em;
border: 1px solid black;
margin-bottom: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="form-input">
<input class="div-input">
<button type="submit">Submit</button>
</form>
<div class="output"></div>
you can use this to show your text anywhere on page
<input id="input-name" oninput="outputname.value = this.value">
<output id="outputname" name="outputname" for="input-name"></output>
You can test it here
If you add an eventlistener to the input, you can use that to change the text in your output area on the page. Like this:
const input = document.getElementById('input');
const output = document.getElementById('output');
input.addEventListener('input', (e) => {
output.innerHTML = input.value;
});
<div id="output"></div>
<input type="text" id="input">
HTML:
<p>Input:</p><input id="input" type="text">
<p>Output:<span id="output"></span></p>
Javascript:
// Function To Select Element
function $(element) {
return document.querySelector(element);
}
// We will get the input when calling this function
function getInput() {
return $('#input').value;
}
// The output will be displayed
function output() {
$('#output').innerHTML = getInput();
}
// This function will start our code
function init() {
output();
}
// On keyup our code will initiate
$('#input').addEventListener('keyup', init);
You can test it here: https://codepen.io/anon/pen/ReyGaO?editors=1111
People are downvoting you because this can be done with very basic JavaScript, and questions like this are very unusual because anyone doing a basic JavaScipt course will probably be able to do this.
Theoretically speaking: you can put an input element and a button on the html page, plus an empty div. You can set an event for the button or even for the input for live updating while typing, and write an event handler function to change the content of the empty div. You can either set its content or add a new child to it, so that the previous content still remains.
Practical example: (The code below is live at https://codepen.io/bradib0y/pen/YJLGrb )
<!DOCTYPE html>
<html>
<body>
<p>Click the button to add a new post.</p>
<input id="NewPostField" type="text" value="Some text">
<button onclick="myFunction()">Add new post</button>
<div id="Posts"></div>
<script>
function myFunction() {
var NewPostField = document.getElementById("NewPostField");
var newPost = document.createElement("p");
newPost.innerHTML = NewPostField.value;
var Posts = document.getElementById("Posts");
Posts.appendChild(newPost);
}
</script>
</body>
</html>
you can do it by this
<input id="mainInput" oninput="output.value = this.value">
<output id="output" name="output" for="input-name"></output>
click here to view in jsFiddle

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>

inserting divs with 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>";

Event over a margin

Having:
<div id="outerDiv">
<div id="innerDiv" style="margin: 10px">Content goes here</div>
</div>
I want to identify those mouse events that happen outside innerDiv but inside outerDiv (said in a different way, those events over the innerDiv margin).
This is easy to achieve if I add outerDiv a padding or a border, but I would like to know if there is another way to do this without having to add extra pixels to outerDiv.
Thanks
Using jQuery I would do the following
$("#outerDiv").bind("event", function(e) {
if ($(e.target).closest("#innerDiv")) {
alert("from inner div");
}
else {
alert("from outer div only");
}
});
Explanation:
#outerDiv will get a bubbled event. If the event's target or target's ancestor is #innerDiv then we know it originated within the inner div. Otherwise it did not. Since it hit #outerDiv we know that it happened somewhere in #outerDiv but not in #innerDiv
This can be achieved by use of a flag:
<div id="outerDiv" style="border:thin solid red;">
<div id="innerDiv" style="border:thin solid blue; margin: 10px;">Content goes here</div>
</div>
<script language="javascript">
var flag = false;
document.getElementById("outerDiv").onclick = function(){
if (flag) {
flag = false;
return false;
}
alert("Clicked outerDiv");
}
document.getElementById("innerDiv").onclick = function(){
flag = true;
alert("Clicked innerDiv");
}
</script>
The essence is that the event for innerDiv will fire first. If so, prevent the event for outerDiv.
The technique works for onmousedown, onmouseup and onmousemove.

Categories