JavaScript addEventListener only for outerDiv - javascript

i have a question about JavaScript addEventListener,
i have two div and in this divs there is a input text.
(please with JavaScript)
i want to register a click only for div not for the input.
<div id="deneme">
<input style="margin: 10px;" type="textbox" />
<div id="new"></div>
</div>
JavaScript:
var divTag = document.getElementsByTagName("div");
for (var i = 0; i < divTag.length; i++) {
if (divTag[i].tagName == "DIV" || divTag[i].tagName == "div") {
if (divTag[i].addEventListener) {
divTag[i].addEventListener('click', redirect,false);
}
else if (divTag[i].attachEvent) {
divTag[i].attachEvent('on' + 'click',redirect);
}
}
}
function redirect(e) {
alert("redirect");
e.stopPropagation();
}
CSS :
#deneme {
width:200px;
height:200px;
background-color:yellow;
}
#new{
width:20px;
height:20px;
background-color:green;
}
can you help me?
Thanks in advance.

If you only have two divs, use document.getElementById instead of getElementsByTagName. You can add the two elements to an array and still iterate over them with your loop.
Otherwise, you can modify your event handler to check that e.target isn't the input.
As a side note, if you're going to be doing a lot of event handling, consider using jQuery. It'll make your life easier in that you do not need to worry about cross-browser compatibility.

You will need to move the input outside the outer div and use CSS to reposition the input above that div. See this Fiddle.
<input style="margin: 10px;" type="textbox" />
<div id="deneme">
<div id="new"></div>
</div>
input {
position: absolute;
}
Edit: Okay, if you cannot move the input as suggested above, you need to test which element triggered the event. I updated the fiddle accordingly.
function is(type, obj) {
// source: http://bonsaiden.github.io/JavaScript-Garden/#the-class-of-an-object
var class = Object.prototype.toString.call(obj).slice(8, -1);
return obj !== undefined && obj !== null && class === type;
}
function redirect(e) {
if ( is('HTMLInputElement', e.target) ) {
return false;
}
alert("redirect");
e.stopPropagation();
}

Not that I like such kind of solution, but if you only want to redirect from the div you can check what kind of element has been pressed, by getting the target and its constructor name.
Code (HTML):
<div id="deneme">
<input style="margin: 10px;" type="textbox" />
<div id="new"></div>
</div>
Code (JS):
var divTag = document.getElementsByTagName("div");
for (var i = 0; i < divTag.length; i++) {
if (divTag[i].tagName == "DIV" || divTag[i].tagName == "div") {
if (divTag[i].addEventListener) {
divTag[i].addEventListener('click', redirect,false);
}
else if (divTag[i].attachEvent) {
divTag[i].attachEvent('on' + 'click',redirect);
}
}
}
function redirect(e) {
if (e.target.constructor.name == "HTMLDivElement") {
alert("redirect");
}
e.stopPropagation();
}
Working fiddle:
http://jsfiddle.net/d5z8zgf0/

You may want to check out JQuery for your solution. Try something like:
$("#deneme").click(function(){
alert("The div was clicked." /* Or do something else */);
});
Also there may be a similar question here: addEventListener vs onclick

Related

JavaScript and HTML to show or hide an element

I think this is very easy, but I just can't seem to twig it at the moment. I want to use a JavaScript function to set the visibility of an HTML tag.
I realise the below is wrong as hidden doesn't take a boolean. I'm just struggling to click what the easiest way to do it is?
So I have some script like this:
<script>
function evaluateBoolean() {
if (location.hostname.indexOf("someval" > 0) {
return true;
} else {
return false;
}
}
</script>
And I wanted to use it something like this:
<div hidden="evaluateBoolean()">
this will be shown or displayed depending on the JavaScript boolean
</div>
I would recommend doing it by altering the display style in the JavaScript code.
const el = document.getElementById('container');
const btn = document.getElementById('btn');
btn.addEventListener('click', function handleClick() {
if (el.style.display === 'none') {
el.style.display = 'block';
btn.textContent = 'Hide element';
} else {
el.style.display = 'none';
btn.textContent = 'Show element';
}
});
You have a div with id: myDIV
<div id="myDIV" class="card-header">
Hello World
</div>
You then call this Javascript function to show the element:
function showDiv() {
document.getElementById('myDIV').style.display = "block";
}
and this one to hide it:
function hideDiv() {
document.getElementById('myDIV').style.display = "none";
}
Note, that you can hide a div by:
<div id="myDIV" class="card-header" style="display:none">
Hello World
</div>
And then call the function to show it.
You trigger must be outside of the element which you hide. because if hided you cant even clicked. The js function classList toggle would be good.
function evaluateBoolean() {
const d = document.querySelector('.w div');
d.classList.toggle('hide');
}
.w {
height: 40px;
background: yellow;
}
.hide {
display: none;
}
<div class="w" onclick="evaluateBoolean()">
<div> this will be shown or displayed depending on the javascript boolean </div>
</div>
You can't explicitly run js in your html, if you aren't using any framework like angular or react, where property binding is allowed.
For achieving your intentions with js you can use this approch:
Add to your div an id:
<div id="myDiv"> Toggled div </div>
In your js script modify your function evaluateBoleean() to show/hide the element:
function evaluateBoolean() {
const div = document.querySelector("#myDiv");
if (location.hostname.indexOf("someval" > 0) {
div.hidden = true;
} else {
div.hidden = false;
}
There's a very easy option:-->
having a blank text
firsly replace the html code with this:-->
<div hidden="evaluateBoolean()" id="ThingToBeHidden"> this will be shown or displayed depending on the javascript boolean </div>
and put js code:-->
document.getElementById("ThingToBeHidden").innerHTML = "";
So you have assigned the div to have it's special id which none other element has.
So now the js code selects the div with that id and then sets the context of it to blank.
If you want the text to appear again, the js code is:-->
document.getElementById("ThingToBeHidden").innerHTML = "this will be shown or displayed depending on the javascript boolean";
You can hide an element in several ways (using jQuery):
const o = $(cssSelectorForElementToStyle);
$(o).hide();
$(o).toggle();
$(o).css('display', 'none');
$(o).addClass('css_class_for_hiding_stuff');
Here using vanilla JavaScript:
const o = document.querySelector(cssSelectorForElementToStyle);
o.style.display = 'none';
o.classList.add('css_class_for_hiding_stuff');
But your question doesn't point out exactly when you are going to make this check. So let's assume you are going to check the boolean value once when the page is loaded and hide or show a given element according to that value:
$(document).ready(
() => {
if (evaluateBoolean() === true) {
// do nothing in this case
} else {
$('#elementWithThisId').css('display', 'none');
}
}
);
Without jQuery:
document.addEventListener("DOMContentLoaded", function() {
if (evaluateBoolean() === true) {
// do nothing in this case
} else {
document.querySelector('#elementWithThisId').style.display = 'none';
}
});

How to remove all children of contenteditable element?

I need to delete all children of a div after clicking enter.
There is a div and event listener below.
<div id = "area" contenteditable="true"></div>
document.onreadystatechange = function(){
if(document.readyState == 'complete'){
document.getElementById("area").addEventListener("keypress" , public_mode);
}
function public_mode(){
var key = window.event.keyCode;
if (key == 13) {
sendMessage();
}
}
function sendMessage(){
var area = document.getElementById("area");
while (area.firstChild) {
area.removeChild(area.firstChild);
}
}
As you can see the contenteditable elements is added an element in according with clicking enter - it depends on browser what element will be added.In my case I use chrome and here are inserted div.
So, the result after clicking enter on the area but without removing
<div id = "area" contenteditable = "true">
Sckoriy
<div></div>
</div>
and , with removing
<div id = "area" contenteditable = "true">
<div></div>
<div></div>
</div>
But , the needed result is
<div id = "area" contenteditable = "true">
//Empty
</div>
The code mostly works, however there were two main issues.
keyCode is deprecated. you should be using key which turns the syntax of searching for a key into looking for a string. This means instead of 13 you just check to see if key is Enter.
Secondly you need to pass the event to your public_mode function so that you can read the key that has been pressed when the event occurs. You also need to use preventDefault to prevent it from adding a new line after removing everything from the original contentEditable area when it does detect Enter
document.onreadystatechange = function() {
if (document.readyState == 'complete') {
document.getElementById("area").addEventListener("keypress", public_mode);
}
function public_mode(event) {
var key = event.key;
if (key === "Enter") {
event.preventDefault();
sendMessage();
}
}
function sendMessage() {
var area = document.getElementById("area");
while (area.firstChild) area.removeChild(area.firstChild);
}
}
#area {
min-width: 100vw;
border: 1px solid black;
}
<div id="area" contenteditable="true"></div>
You could just set the innerHTML proprety to an empty string;
area.innerHTML = '';
target the dom by id
var s = document.getElementById("area");
save the number of childrens
var num = s.children.length;
and remove the num of childs of element
for(var i=0;i<num;i++){
s.children[0].remove()
}
and inner for some thext
s.innerHTML = "";
Pass the key event as an argument to your function.
Also, if you do not want the newline entered in your div, you can prevent the event from continuing with event.preventDefault().
document.onreadystatechange = function() {
if (document.readyState == 'complete') {
const area = document.getElementById('area')
area.addEventListener('keypress', public_mode);
area.focus();
}
}
function public_mode(event) {
if (window.event.keyCode == 13) {
sendMessage();
event.preventDefault();
}
}
function sendMessage() {
const area = document.getElementById('area');
while (area.firstChild) {
area.removeChild(area.firstChild);
}
}
<div id="area" contenteditable="true">Press Enter to erase me!</div>

Javascript body overflow: hidden

I have been experimenting to try to get this to work.
I have 2 checkboxes acting as part of my mobile CSS navigation menu for either side. I have a javascript that prevents more than 1 checkbox to be open at a time. It works.
Now I am trying to add an overflow:hidden to the body when either 1 of the checkboxes is checked, obviously if nothing is checked then to remove overflow:hidden, but I can't seem to get the first part to work.
I am fairly new to Javascript so any help would be appreciated. Thanks!
function selectOnlyThis(id){
var myCheckbox = document.getElementsByName("nav-check");
Array.prototype.forEach.call(myCheckbox,function(el){
if (id != el)
{
el.checked = false;
}
});
if (id.checked == false)
{
id.checked = false;
} else
{
id.checked = true;
}
if (id.checked == true)
{
$('body').css("overflow", "hidden");
}
}
// Click, scroll to the top of the document
function topFunction() {
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
}
<div class="l-btn">
<input id="lger" type="checkbox" name="nav-check" onclick="selectOnlyThis(this)"/>
<label for="lger" onclick="topFunction()"><span></span><span></span</label>
</div>
<div class="r-btn">
<input id="rger" type="checkbox" name="nav-check" onclick="selectOnlyThis(this)"/>
<label for="rger" onclick="topFunction()"><span></span><br/><div>Location</div></label>
</div>
This will do
It takes all the changes made to any checkbox and checks if the id is rger or lger and the checkbox is checked or not, then it changes the css with the jquery .css() method.
<div class="r-btn">
<input id="rger" type="checkbox" name="nav-check" />
<label for="rger" onclick="topFunction()"><span></span><br/><div>Location</div></label>
</div>
$("input:checkbox").on('change', function () {
if (($(this).attr('id')=='rger' || $(this).attr('id')=='lger') && $(this).prop('checked')) {
$('body').css("overflow", "hidden");
}
else
$('body').css("overflow", "visible");
});
Refer this fiddle.
It looks like your coming from a different programming language? :)
You will love javascript, for example a slim function for your first checkbox.
function selectOnlyThis = ({ target }) => {
const { id, checked } = target;
id === 'rger' && checked && $('body').css("overflow", "hidden");
}

bind javascript function to input control on window load

I amm develloping an web form with multiple text box with same css class.
and i want to bind a specific method to all these textboxes who use that class.
belows are my codes
window.onload = function ()
{
var tObj = document.getElementsByClassName('exa');
for (var i = 0; i < tObj.length; i++) {
tObj[i].onblur(convertAmount(event,this));
}
}
the another function 'convertAmount()' is below
function convertAmount(evt, obj) {
if (obj.value != "") {
var num = parseFloat(obj.value);
num = Math.round((num + 0.00001) * 100) / 100;
obj.value = num.toFixed(2);
}
else {
obj.value = "0.00";
}
}
html codes
<div>
<input type="text" id="finalvalue" class="exa"/>
<input type="text" id="grossvalue" class="exa"/>
<div>
when browser load first time only '0.00' values are coming on those text boxes. but when i type some values on those text boxes and press tab its not working! please help what is wrong here
As commented before, you should assign a eventHandler and not pass it as callback.
So you code would be:
tObj[i].onblur = convertAmount.bind(this, event, this);
Also, event is default argument for any eventListener and current object/element is automatically binded to it, so above code can be simplified to
tObj[i].onblur = convertAmount;
This will bind the context and you will get all properties in this.
Sample Fiddle
Note: you should use addEventListener instead. onBlur = will replace all previous events. addEventListener will add another one.
Sample Fiddle
I hope this link helpful to you.
<div>
<input type="text" id="finalvalue" class="exa"/>
<input type="text" id="grossvalue" class="exa"/>
<div>
$(document).ready(function(){
$('.exa').each(function(index,value){
$(this).attr('onblur',convertAmount(event,$(this)))
})
})
function convertAmount(evt, obj) {
if (obj != "") {
$(obj).val('0.00')
}
else {
$(obj).val('0.00')
}
}

show/hide div when user inputs text into text area?

I am trying to toggle a div so it shows and hides when a user enters text into textarea.
i am using the below code and its not working for me, can anyone please show me why? thanks
html:
<head>
<script>
$(document).ready(function() {
$("#cname").keyup(function() {
if ($("#cname").val() > 8) {
$('#cname2').toggle("slow");
}
});
});
</script>
</head>
<form>
<input type="text" id="cname" name="cname" class="field">
<div id="cname2"></div>
</form>
css:
#cname2{
width:30px;
height:30px;
position:absolute;
margin-top:-13px;
margin-left:400px;
background-image: url('tick.png');
background-repeat:no-repeat;
background-position:right;
display:none;
}
so apparently my above code doesnt work in IE 9, but i should be able to achieve what i am trying to do by using this code, but can someone please show me where i place my div ID/how i adapt it to work for me?
var activeElement = null;
var activeElementValue = null;
// On focus, start watching the element
document.addEventListener("focusin", function(e) {
var target = e.srcElement;
if (target.nodeName !== "INPUT") return;
// Store a reference to the focused element and its current value
activeElement = target;
activeElementValue = target.value;
// Listen to the propertychange event
activeElement.attachEvent("onpropertychange", handlePropertyChange);
// Override .value to track changes from JavaScript
var valueProp = Object.getOwnPropertyDescriptor(
HTMLInputElement.prototype, 'value');
Object.defineProperty(activeElement, {
get: function() { return valueProp.get.call(this); },
set: function(val) {
activeElementValue = val;
valueProp.set.call(this, val);
}
});
});
// And on blur, stop watching
document.addEventListener("focusout", function(e) {
if (!activeElement) return;
// Stop listening to propertychange and restore the original .value prop
activeElement.detachEvent("onpropertychange", handlePropertyChange);
delete activeElement.value;
activeElement = null;
activeElementValue = null;
});
function handlePropertyChange(e) {
if (e.propertyName === "value" &&
activeElementValue !== activeElement.value) {
activeElementValue = activeElement.value;
// Fire textchange event on activeElement
}
};
$(document).ready(function() {
$("#cname").keyup(function() {
if ($("#cname").val().length > 8) {
$('#cname2').show();
} else {
$('#cname2').hide();
}
});
});
One possible approach (demo):
$(document).ready(function() {
$("#cname").on('input', function() {
$('#cname2')[this.value.length > 8 ? 'hide' : 'show']('slow');
});
});
Here I assumed that in cname2 container there's some warning message, that has to be shown if length of text input is 8 or less characters. Note also that I've used oninput handler, not keyup: as it allows me to process mouse-driven cut-and-paste as well as direct input. The only drawback is that IE8 doesn't support this event (and IE9 support for it is rather buggy, as handler is not fired when character is removed from text input).
Use this Javascript function
var z = document.getElementById('cname');
z.onkeyup = function(){
document.getElementById('cname2').innerHTML = z.value;
}
Your HTML:
<input type='text' name='cname' class='field' id='cname'>
<div class='cname2' id='cname2'></div>
Checkout here: http://jsfiddle.net/iamsajeev/Q9LPv/
$(document).ready(function() {
$("#cname").keyup(function() {
if ($("#cname").val() > 8) {
$('#cname2').fadeIn("slow");
}
else
{
$('#cname2').fadeOut("slow");
}
});
});
http://jsfiddle.net/5EjP7/2/
I hope that helps
Try the following script:
$(document).ready(function() {
$("#cname").keyup(function() {
if ($("#cname").val().length > 8) {
$('#cname2').toggle("slow");
}
});
});

Categories