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.
Related
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....
I have made a JavaScript tab view of a simple HTML page.
I've added onClick functions for header tags using JavaScript via nodes.
The onClick function performs a function called showTab passing on this as a parameter.
I understand that this is [object window].
The header tag onClick functions are set as shown below:
node.onclick = function() { showTab(this); };
The showTab function is as follows:
function showTab(e)
{
var node = (e && e.target) || (window.event && window.event.srcElement);
alert(node.innerHTML);
}
Everything works fine, when i click on one of the headers, an alert appears with its innerHTML.
However, I did use a little help from Google to achieve this. And I would like some help understanding exactly what this line means:
var node = (e && e.target) || (window.event && window.event.srcElement);
I did my own research and saw it can be considered as the equivalent as sender in C#.
But I would like to know thoroughly how it works and what it is referring to and how it knows which node is calling the showTab function as there are 3 header tags that perform the same function, all without id's.
Ah, the joys of dealing with Events and browser.
The Trident Engine (Internet explorer and others based on that engine) deals with events differently than most (all?) of the other browsers.
<html>
<head>
<title>Test</title>
</head>
<body>
<button id="test_button">Click me</button>
<script>
// UGLY, UGLY, UGLY... don't really use this
var button = document.getElementById("test_button");
if (window.attachEvent) {
button.attachEvent("onclick", showTab);
} else {
button.addEventListener("click", showTab);
}
function showTab(e)
{
// Most browsers pass the event as 'e'
// Microsoft puts the event in window.event
// Either way, event will now point to the object we want.
var event = e || window.event;
// Once again, the different browsers handle the `target` property differently.
// Target should now point to the right event.
var target = event.target || event.srcElement;
alert(target.innerHTML);
}
</script>
</body>
This line:
var node = (e && e.target) || (window.event && window.event.srcElement);
is equivalent to this logic:
var node;
if (e && e.target) {
node = e.target;
} else if (window.event && window.event.srcElement) {
node = window.event.srcElement;
} else {
node = undefined;
}
The purpose of this code is to handle the fact rhat older versions of IE don't pass the event structure to an event handler. Instead, it is stored in a global variable window.event and the event target is also stored in a difference property of the event.
It is a bit more common (and I think more readable) to do something like this:
function showTab(e) {
// get the event data structure into e
e = e || window.event;
// get the source of the event
var node = e.target || e.srcElement;
alert(node.innerHTML);
}
In reality, any decent size project should use a library function for abstracting the differences in event handlers so that this browser-specific code only has to be one place in the project or use a pre-built library like jQuery for this type of thing. Here's a cross-browser event handler:
// refined add event cross browser
function addEvent(elem, event, fn) {
if (typeof elem === "string") {
elem = document.getElementById(elem);
}
function listenHandler(e) {
var ret = fn.apply(this, arguments);
if (ret === false) {
e.stopPropagation();
e.preventDefault();
}
return(ret);
}
function attachHandler() {
// older versions of IE
// set the this pointer same as addEventListener when fn is called
// make sure the event is passed to the fn also so that works the same too
// normalize the target of the event
window.event.target = window.event.srcElement;
var ret = fn.call(elem, window.event);
if (ret === false) {
window.event.returnValue = false;
window.event.cancelBubble = true;
}
return(ret);
}
if (elem.addEventListener) {
elem.addEventListener(event, listenHandler, false);
} else {
elem.attachEvent("on" + event, attachHandler);
}
}
It's getting the dom element which was clicked, either e.target for standards compliant browsers or window.event.srcElement (could be e.srcElement instead for newer IE)
see: http://www.quirksmode.org/js/events_properties.html
When i'm handle click to edit area. i use folowing function
Function.prototype.closureListener = function() {
var __method = this, args = bkLib.toArray(arguments), object = rgs.shift();
return function(e) {
e = e || window.event;
if(e.target) { var target = e.target; } else { var target = e.srcElement };
return __method.apply(object, [e,target].concat(args) );
};
}
and add event
this.elm.addEvent('mousedown',this.selected.closureListener(this))
But when i click at the end of the line
asdasdasd<b>sdasdasdasd<b>
sometimes it's select like a target all body(as Element) or only sdasdasdasd.
What should i add that he took only sdasdasdasd but not all body.
P.S When i click somewhere in the middle it's always takes sdasdasdasd
P.S.S nicEdit i'm using this nicEdit panel.
In Firefox 6 I tried to get the target element on which the event occurred, but it does not show any element and it shows undefined in alert. Tried to debug it using the Firebug tool and found the attribute "target" missing for the event object. Can anyone help me out? I do have the code below:
function getSource(event)
{
if(!event)
{
field = window.event.srcElement;
alert(field);
}
else
{
field = event.target;
alert(field) //Getting undefined in FF6
}
}
Edited Portion:
document.onkeypress = getSource;
document.onmouseup = getSource;
Any help would be appreciated.
Try the code below
function getSource(e)
{
if(!e)
e = window.event;
field = evt.srcElement || evt.target;
alert(field);
return true;
}
Hope this helps you.
Test this in Fx 6:
<script type="text/javascript">
window.onload = function() {
document.getElementById('d0').onclick = showTarget;
}
function showTarget(e) {
e = e || window.event;
var target = e.target || e.srcElement;
alert(target.tagName);
}
</script>
<div id="d0">
<p>click on me</p>
</div>
It should alert "P".
As also explained in the similar question, change the function to this:
function getSource(evt)
{
if(!evt)
evt = window.event;
if (evt) {
field = evt.srcElement || evt.target;
alert(field);
return true;
}
alert("event not found");
return false;
}
function getSource(ev) {
var el=(ev=ev||window.event).target||ev.srcElement;
alert(el+" "+el.tagName);
}
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;
}
};