I'm trying to return a div's background image back to its default using a onmouseleave method. Here is the HTML and JS:
<script type="text/javascript">
function displayImage(event) {
event = event || window.event;
var targetElement = event.target || event.srcElement;
if (targetElement.tagName == "IMG") {
console.log(document.getElementById("viewer"));
document.getElementById("viewer").style.backgroundImage = 'url(' + targetElement.getAttribute("src") + ')';}
}
function leaveImage(event){
event = event || window.event;
var targetElement = event.target || event.srcElement;
if (targetElement.tagName != "IMG") {
document.getElementById("viewer").style.backgroundImage: URL();
}
}
where displayImage and leaveImage are called with the methods in the same HTML div tag:
<div class="thumbnails" onmouseover="displayImage(event)">
In essence, I want to return the "viewer" id'd div element's background image to its default on mouseleave (creating two separate functions). Am I going about it the right way?
Thank you all!
Alright, firstly; it's showing [Object HTML Collection] because you are calling getElementsByTagName, Notice it says Elements, so you are getting every single p tag on your website, what you want instead is to get just a single one. The solution could be giving the p tag an ID and then use getElementById, then you would only get the single element.
Second, you need to save the original p tag text somewhere, here is an example saving it in a variable:
HTML:
<p id="tip">Hover over the image to display larger</p>
Javascript:
var originalText; // Notice this is outside the functions
function displayImage(event) {
event = event || window.event;
var targetElement = event.target || event.srcElement;
originalText = document.getElementById("tip").innerHTML;
var altText=targetElement.getAttribute("alt");
document.getElementById("viewer").innerHTML = altText;
if (targetElement.tagName == "IMG") {
console.log(document.getElementById("viewer"));
document.getElementById("viewer").style.backgroundImage = 'url(' + targetElement.getAttribute("src") + ')';
}
}
function leaveImage(event){
event = event || window.event;
var targetElement = event.target || event.srcElement;
document.getElementById("viewer").innerHTML = originalText;
if (targetElement.tagName != "IMG") {
document.getElementById("viewer").style.backgroundImage= URL();
}
}
I think this line should have an "=" instead of ":":
document.getElementById("viewer").style.backgroundImage = URL();
Maybe that's the only issue....
Related
I need to translate this jquery to vanilla js:
$(document).on('click', 'a', function(){
//do something
});
I've tried with
document.addEventListener('click', function(e) {
if(e.target.tagName === 'A')
{
//do something
}
});
But it's not working if the element clicked is a child of an a, for example
<a href="...">
<!-- if I click on the image, e.target.tagName === 'IMG' -->
<img src="img.jpg">
</a>
I can't use document.getElementsByTagName('a'), because It should work even with those created dynamically.
Also, I'd need to access the href property of the a.
What is the simplest way to do this?
In modern browsers you can use Element.closest() - Not supported in IE
document.addEventListener('click', function(e) {
e.preventDefault();
if (Element.prototype.closest) {
if (e.target.closest('a')) {
console.log('found')
}
} else {
//else the long way
var el = e.target;
while (el && el.tagName != 'A') {
el = el.parentNode;
}
if (el) {
console.log('found')
}
}
});
<a href="...">
This and image
<img src="img.jpg">
</a>
Not here
Take the DOM for a Walk
You have a anchor tag that contains an image and you want catch click events.
The currentTarget property (as suggested in a comment) is not useful since the handler is attached to document, i.e., currentTarget = document.
The solution is to catch clicks on the image and then walk up the DOM tree to check if the parent element is an anchor tag.
The code below illustrates how you might accomplish this check using a while loop. It also displays target, currentTarget, and parentElement. As you can see, clicking on the text within the link produces different output than clicking on the image.
Run the snippet to try
document.addEventListener('click', function(e) {
var t = e.target;
while (t) {
if (t.tagName === 'A') {
// do something ...
debug.innerHTML += (
'target = ' + e.target +
'\ncurrentTarget = ' + e.currentTarget +
'\nparentElement.tagName = ' + t.tagName + '\n'
);
break;
}
t = t.parentElement;
}
});
// dynamically add link with image
var a = document.createElement('A');
a.href = 'javascript:void(0)';
a.innerHTML = 'Click Me!<br><img src="http://lorempixel.com/100/50">';
document.getElementById('content').appendChild(a);
img {width:100px;height:50px;background-color:aliceblue;}
<span id="content"></span>
<xmp id="debug"></xmp>
Is it possible to attach a new event to every links of a page recursively? Currently I'm using the following code:
var linkHandler = function (e) {
e = e || window.event;
var element = e.target || e.srcElement;
console.log("Element clicked, type: "+element.tagName);
if (element.tagName == 'A') {
console.log("Catched "+element.href);
element.href = url(element.href);
}
};
document.addEventListener("click", linkHandler, true);
But it only works if I directly click on a link. For example here, only the click on "Work" of the second link works.
<strong>Doesn't work</strong>
Work <strong>Doesn't</strong>`
Is there another possibility ?
I've got the following JavaScript code to track clicks on a div:
var anchor = document.getElementById('clickMe');
if (anchor.addEventListener) {
anchor.addEventListener('click', clickHandlerOpen, false);
} else if (anchor.attachEvent) {
anchor.attachEvent('onclick', function () {
return clickHandlerOpen.apply(anchor, [window.event])
});
}
My html looks like this:
<div id="clickMe">
<div id="someContent"><p>hello</p></div>
<div id="closeMe">X</div>
</div>
How can i exclude the id closeMe from the above click handler? I want the closeMe to have its own.
Please note that i do not want to use jQuery.
Check the target.id of the clicked element inside your function:
clickHandlerOpen(event) {
//Satisfy IE8
event = event || window.event; // get window.event if argument is falsy (in IE)
// get srcElement if target is falsy (IE)
var targetElement = event.target || event.srcElement;
if (targetElement.id == 'closeMe') return false;
//your code here
}
I want to get href attribute when a use clicks on a URL.
I've tried with:
var e = clickedElement || window.event;
var t = e.target || e.srcElement;
alert(t.href);
This is working fine in Chrome and Firefox, but there's a problem with IE; its give an error null.
What is possible solution to get href from event object?
Depends what clickedElement is, given that its either the event object argument placeholder or a this argument;
function event_obj(event) {
if (!event) var event = window.event;
var element = event.target || event.srcElement;
alert(element.href);
return false;
}
function element_obj(element) {
alert(element.href)
return false;
}
.
.
foo
bar
Use this function to get the event target
function getEventTarget(event) {
var targetElement = null;
try {
if (typeof event.target != "undefined") {
targetElement = event.target;
}
else {
targetElement = event.srcElement;
}
} catch (ex) { alert("getEventTarget failed: " + ex); }
return targetElement;
};
Then call it when you trigger the event
function evtrigger(ev) {
alert(getEventTarget(ev).href);
}
Note the getEventTarget() function works for all events so the DOM object returned can be manipulated any way you like, not just to get the href.
I have code like:
document.onmousedown = function(){
alert('test');
}
Now, except the element with ID "box", clicking should call this function, i.e. the equivalent of jQuery's .not() selector.
The jQuery code would be:
$(document).not('#box').mousedown(function(){
alert('test');
});
How can I achieve the same thing without using jQuery?
Edit: I don't want jQuery code, but i want an action similar to the .not() selector of jQuery in Javascript.
Edit: I am making an addthis-like widget. It is a 10kb file which will show a popup when a text is selected. It will not use jQuery.
In my case, when a text is selected, a popup is shown. When the document is clicked somewhere other than the widget, the widget should disappear.
To do this properly, you need to check whether e.target || e.srcElement or any of its parents has id === 'box'.
For example: (with jQuery)
$(document).mousedown(function(e) {
if ($(e.target).closest('#box').length)
return;
//Do things
});
Without jQuery:
function isBox(elem) {
return elem != null && (elem.id === 'box' || isBox(elem.parentNode));
}
document.onmousedown = function(e) {
e = e || window.event;
if (isBox(e.target || e.srcElement))
return;
//Do things
};
Alternatively, you could handle the mousedown event for the box element and cancel bubbling.
Here's one way that should work:
document.onmousedown = function(e){
var event = e || window.event;
var element = event.target || event.srcElement;
if (target.id !== "box") { alert("hi"); }
}
or if you would like it to be reusable with different ids:
function myNot(id, callback) {
return function (e) {
var event = e || window.event;
var element = event.target || event.srcElement;
if (target.id !== id) { callback(); }
}
}
and to use it:
document.onmousedown = myNot("box", function () {
alert("hi");
});
The cleanest way I can come up with for what you're trying to do is to set a document.onmousedown event and then halt event propagation on the box.onmousedown event. This avoids creating a large number of onmousedown events all over the document, and avoids having to recurse through the entire parent hierarchy of a node every time an event is triggered.
document.onmousedown = function() {
alert("Foo!");
};
document.getElementById("box").onmousedown = function(e) {
alert("Bar!");
if (e.stopPropagation) {
e.stopPropagation();
} else {
e.cancelBubble = true;
}
};