Click HTML except one element, without using jQuery - javascript

I show us the code:
(function (){
var element = document.getElementById('bar'), hideElement = document.getElementById('foo'),
var html = document.getElementsByTagName('html')[0];
tool.onclick = function() {
hideElement.style.display = 'block';
html.onclick = function() {
hideElement.style.display = 'none';
}
}
})();
This piece of code work's fine, but, after clicking html, I can not reopen the hidden element.
I want to click the html element and give display:none to hideElement, then to click the element id="bar", give to the hidden element display:block, but instead of click the element foo, click the html element. What I can do?
Oh, i need help WITHOUT JQUERY, thanks :)
EDIT: something like that : click on body except some other tag not working , but without JQuery,

I'm not sure it's going to answer your question, but here it is: how to handle an event on the body except one element:
document.documentElement.onclick = function(e) {
var evt = e || window.event, // IE...
target = evt.target || evt.srcElement // IE again...
// There, "target" is the element clicked. See where I'm going?
if (target.id !== "foo") {
// Do w/e you want if the page was clicked, except for "foo"
}
}
This is the concept of "event bubbling". You can listen to one element and all its children at once, and get the target as specified in the code up there.

First, you don't appear to be defining tool anywhere that I can see.
Second, you forgot .style in hideElement.display (should be hideElement.style.display).
Third, document.getElementsByTagName('html')[0] is redundant. Just use document.documentElement instead.

Change
html.onclick = function() {
hideElement.display = 'none';
}
to
html.onclick = function() {
hideElement.style.display = 'none';
}

Related

pass/propagate event.target of parent element [duplicate]

I am trying to change the innerHTML of my page to become the innerHTML of the element I click on, the only problem is that i want it to take the whole element such as:
<section class="homeItem" data-detail="{"ID":"8","Name":"MacBook Air","Description":"2015 MacBook A…"20","Price":"899","Photo":"Images/Products/macbookAir.png"}"></section>
Whereas the code that i have written in javascript:
function selectedProduct(event){
target = event.target;
element = document.getElementById("test");
element.innerHTML = target.innerHTML;
}
will target the specific element that i click on.
What i would like to achieve is when i click on anywhere in the <section> element, that it will take the innerHTML of the whole element rather than the specific one that i have clicked.
I would presume it is something to do with selecting the parent element of the one that is clicked but i am not sure and can't find anything online.
If possible i would like to stay away from JQuery
I think what you need is to use the event.currentTarget. This will contain the element that actually has the event listener. So if the whole <section> has the eventlistener event.target will be the clicked element, the <section> will be in event.currentTarget.
Otherwise parentNode might be what you're looking for.
link to currentTarget
link to parentNode
To use the parent of an element use parentElement:
function selectedProduct(event){
var target = event.target;
var parent = target.parentElement;//parent of "target"
}
handleEvent(e) {
const parent = e.currentTarget.parentNode;
}
function getParent(event)
{
return event.target.parentNode;
}
Examples:
1. document.body.addEventListener("click", getParent, false); returns the parent element of the current element that you have clicked.
If you want to use inside any function then pass your event and call the function like this :
function yourFunction(event){
var parentElement = getParent(event);
}
var _RemoveBtn = document.getElementsByClassName("remove");
for(var i=0 ; i<_RemoveBtn.length ; i++){
_RemoveBtn[i].addEventListener('click',sample,false);
}
function sample(event){
console.log(event.currentTarget.parentNode);
}
$(document).on("click", function(event){
var a = $(event.target).parents();
var flaghide = true;
a.each(function(index, val){
if(val == $(container)[0]){
flaghide = false;
}
});
if(flaghide == true){
//required code
}
})

'onclick' event function in document is never being fired

The problem I'm facing is that currently I have 2 elements, one is visible by default and the other one is hidden. When a button is clicked the state in both elements are exchanged, which means that the element which was not visible not it is and viceversa. What I want to accomplish now is that when I click in any other part of the page except in that given element, the state is reversed.
<script type="text/javascript">
function hidesearch() {
var target = event.target || event.srcElement;
if (event.currentTarget == target) {
document.getElementById('elem1').style.display = "none";
document.getElementById('elem2').style.display = "true";
}
}
function showsearch() {
document.getElementById('elem2').style.display = "none";
document.getElementById('elem1').style.display = "true";
event.stopPropagation();
}
</script>
This is the current code inside my head tag. Tried to add the onclick and onload attributes into the body too but isn't working still.
<h:body onload="hidesearch();"/>"
The page is .xhtml as everything is being coded using JSF + BootsFaces.
Is there anything I'm missing out?
document.getElementById('elem2').style.display = "true";
display property value of element style can be "block", "inline-block", "inline", "none" but "true" value doesn't exist.
Please assign appropriate value one you want.

Can you target an elements parent element using event.target?

I am trying to change the innerHTML of my page to become the innerHTML of the element I click on, the only problem is that i want it to take the whole element such as:
<section class="homeItem" data-detail="{"ID":"8","Name":"MacBook Air","Description":"2015 MacBook A…"20","Price":"899","Photo":"Images/Products/macbookAir.png"}"></section>
Whereas the code that i have written in javascript:
function selectedProduct(event){
target = event.target;
element = document.getElementById("test");
element.innerHTML = target.innerHTML;
}
will target the specific element that i click on.
What i would like to achieve is when i click on anywhere in the <section> element, that it will take the innerHTML of the whole element rather than the specific one that i have clicked.
I would presume it is something to do with selecting the parent element of the one that is clicked but i am not sure and can't find anything online.
If possible i would like to stay away from JQuery
I think what you need is to use the event.currentTarget. This will contain the element that actually has the event listener. So if the whole <section> has the eventlistener event.target will be the clicked element, the <section> will be in event.currentTarget.
Otherwise parentNode might be what you're looking for.
link to currentTarget
link to parentNode
To use the parent of an element use parentElement:
function selectedProduct(event){
var target = event.target;
var parent = target.parentElement;//parent of "target"
}
handleEvent(e) {
const parent = e.currentTarget.parentNode;
}
function getParent(event)
{
return event.target.parentNode;
}
Examples:
1. document.body.addEventListener("click", getParent, false); returns the parent element of the current element that you have clicked.
If you want to use inside any function then pass your event and call the function like this :
function yourFunction(event){
var parentElement = getParent(event);
}
var _RemoveBtn = document.getElementsByClassName("remove");
for(var i=0 ; i<_RemoveBtn.length ; i++){
_RemoveBtn[i].addEventListener('click',sample,false);
}
function sample(event){
console.log(event.currentTarget.parentNode);
}
$(document).on("click", function(event){
var a = $(event.target).parents();
var flaghide = true;
a.each(function(index, val){
if(val == $(container)[0]){
flaghide = false;
}
});
if(flaghide == true){
//required code
}
})

disable onclick event on div when clicking on inside <a> link (No js framework)

I have this piece of code:
<div id="mydiv" onclick="ajax_call()">
Mylink
</div>
I'd like ajax_call() to be called only when clicking on empty space inside div but not on "Mylink". Is it possible without any external javascript framework?
Moreover I have this piece of css:
div#mydiv:hover{
background-color: blue;
}
Is it possible to disable the :hover stylesheet when the cursor is placed over "Mylink" (in order to suggest that clicking on "Mylink" won't trigger ajax_call() but will take to myurl)?
Attach the function at child element with click event, After clicked on child element it's handler stops the immediate propagation, As a result ajax_call() will not be invoked.
HTML
<div id="mydiv" onclick="ajax_call()">
Mylink
</div>
javaScript
function ajax_call(){
alert("empt space");
}
//this function stops the propagation and not triggered above
//function when clicked on child element.
function notCall(event) {
event.stopImmediatePropagation();
return false;
}
DEMO
I'm not sure what you want but if I keep my imagination may be that this work, lucky !
$("div#mydiv a").hover(function(){
$(this).parent().css("background-color","transparent")
})
Sure, what you need is the event target || scrElement
Like
function ajax_call() {
var target = event.target ? event.target : event.srcElement;
if(target.id==="mydiv") { alert("good to go"); }
}
See : http://jsbin.com/qujuxufo/1/edit
Edit/Update ( missed the second part ) - Started to answer this before the q was closed - but might as well as it now ..
For the second part of the question - it is not possible to set parent elements in CSS ( it flows top to bottom ) - for that some more JS is needed.
See http://jsbin.com/cileqipi/1/edit
CSS
#mydiv:hover { background-color:green; color:#fff}
#mydiv.anchorhover, #mydiv.anchorhover:hover { background-color:white;}
Then JS
var _mydiv = document.getElementById("mydiv");
var _mydiv_anchors = _mydiv.getElementsByTagName("a");
function toggleClass() {
var addClass=true, cls="anchorhover";
if((_mydiv.className).indexOf(cls) >= 0){ addClass=false; }
if(addClass) {
_mydiv.className=_mydiv.className+=' '+cls;
} else {
/* remove */
_mydiv.className=_mydiv.className.replace(new RegExp('(\\s|^)'+cls+'(\\s|$)'),' ').replace(/^\s+|\s+$/g, '');
}
}
for(var i=0, len=_mydiv_anchors.length; i<len; ++i) {
_mydiv_anchors[i].onmouseover = toggleClass;
_mydiv_anchors[i].onmouseout = toggleClass;
}
^ That feels like quite a trip compared to how simple jquery abstracts it .. >
$("#mydiv a").hover(function() {
$(this).parent().addClass("anchorhover");
}, function() {
$(this).parent().removeClass("anchorhover");
});
Either way, the principle is : to add a style class to the parent element on mouseover and remove it on mouseout

How can I attach event to a tag which is in string form?

I'm creating html on runtime like this:
var myVar = "<div id='abc'>some clickable text</div>"
Now, I want to attach some event, say onclick, to this div. How can I do that on next line? I'll add this to DOM later.
PS: I've to accomplish this without using JQuery.
Instead of building your div as a string, you'll want to use document.createElement('div'). This way you will have a real dom object, and can get and set it's propeties, including onClick
Will this help? Since you dynamically generate it, you know the control id of the DIV.
document.getElementbyId('abc').onClick = foo;
function foo()
{
alert("All your impl to go here");
}
Try building the div as a DOM element first.
var myVar = document.createElement("div"),
parentDiv = document.getElementById("parent_div");
parentDiv.appendChild(myVar);
myVar.innerHTML = "some clickable text";
if(myVar.addEventListener){
myVar.addEventListener("click", clickFn, false);
}
else if(myVar.attachEvent){
myVar.attachEvent("onclick", clickFn);
}
else{
myVar.onclick = clickFn;
}
The addEventListener method is standard, but not every browser plays nice with the standard.
EDIT: As mentioned, an element must be added to the DOM first.
Or you can use this technique: attach event to the document.body. Then if the event target is not the needed div than just do nothing. It is the same techinque jquery uses for its live function:
// crossbrowser event attachment function
function listen(evnt, elem, func) {
if (elem.addEventListener) {
elem.addEventListener(evnt, func, false);
}
else if (elem.attachEvent) {
var r = elem.attachEvent("on" + evnt, func);
return r;
}
else window.alert('I\'m sorry Dave, I\'m afraid I can\'t do that.');
}
// this is an analog of the jquery.live
var assignLiveEvent = function(id, evnt, callback) {
var handler = function(e) {
e = e || window.event;
e.target = e.target || e.srcElement;
if (e.target.id == id) {
//your code here
callback(e);
}
};
listen(evnt, document.body, handler);
};
var myVar = "<div id='abc'>some clickable text</div>";
assignLiveEvent("abc", "click", function(e) {
//your code here
});
// now you can add your div to DOM even after event handler assignation
Here is demo.
Brian Glaz is totally right but, if for some reason, you really need to do it this way, you have two options:
you can only add events to something that is already in the DOM, using pure javascript, so you would have to include it in the html like:
document.body.innerHTML += myVar;
and then, attach the event with
document.getElementById('abc').addEventListener('click', function(e){
//your code
}, 1);
With jQuery, you could use .live() to attach events to elements that are not yet present in the DOM:
$('#abc').live('click', function(e){
//your code here
});
so you could add the div later...

Categories

Resources