I want to be able write code in the console that allows me to print to the console the inner HTML of any elements I click on within a Web page. This is my code so far.
var findBody = document.querySelector ('body');
function findContent(event) {
findBody.onclick = "findContent(event)";
console.log (event.target.innerHTML);
}
Please be kind, I'm just beginning to write JS. Thanks
You've found body element and written a function. But your function is never called, you have to make browser execute it when event (click) happens.
Basic way to attach event handler is to define on+eventName attribute of the element. Still, it is better to use element.addEventListener method, because you can add as many event listeners to the same element as you want. Also, this method allows to control when event handler is applied during event propagation through the document (nice doc)
Here's basic solution:
// find body element
var findBody = document.querySelector('body');
// define handler function
function findContent(event) {
console.log (event.target.innerHTML);
}
// attach event handler
findBody.addEventListener('click', findContent);
This should work:
var findBody = document.querySelector ('body');
function findContent(event) {
console.log (event.target.innerHTML);
}
findBody.onclick = findContent;
Maybe, You can try this snippet:
function find() {
console.log(event.target.innerHTML);
}
document.onclick = find;
Related
div.onclick = function(data, dom) {
return function() {
if (data.seenAlready == true) { // HACK
$(this).children().toggle();
return;
}
recursiveSearch(data, dom);
// after this onclick, I want to assign it to a toggle like function. no clue how to do it.
}
}(child, mycontainer.appendChild(div));
I'm trying to swap the onclick method after first onclick on a dom element. I've just not had any success, it seems to some sort of closure loss, or something. I'm fine using jQuery.
You have two ways to do this and both ways are by using a jQuery function:
1) Use one API method - this will work just once. You will click it once and then you choose your own second handler and the first one will not fire again e.g.
$(myselector).one(function(){
$(this).click(myotherhandler);
});
Here is the link to this API http://api.jquery.com/one/.
2) You can choose the following way to replace the event handler .
$(myselector).click(function(){
$(this).off();
$(this).click("secondhandler");
});
this will turn the first handler off and will just fire second handler
Check this jsbin:
http://jsbin.com/fekuq/1/edit?html,js,output
I've been struggling with what seems to be a simple problem for a few hours now. I've written a REGEX expression that works however I was hoping for a more elegant approach for dealing with the HTML. The string would be passed in to the function, rather than dealing with the content directly in the page. After looking at many examples I feel like I must be doing something wrong. I'm attempting to take a string and clean it of client Events before saving it to our Database, I thought jQuery would be perfect for this.
I Want:
Some random text click here and a link with any event type
//to become:
Some random text click here and a link with any event type
Here's my code
function RemoveEvilScripts(){
var myDiv = $('<div>').html('testing this Do it! out');
//remove all the different types of events
$(myDiv).find('a').unbind();
return $(myDiv).html();
}
My results are, the onClick remains in the anchor tag.
Here's a pure Javascript solution that removes any attribute from any DOM element (and its children) that starts with "on":
function cleanHandlers(el) {
// only do DOM elements
if (!('tagName' in el)) return;
// attributes is a live node map, so don't increment
// the counter when removing the current node
var a = el.attributes;
for (var i = 0; i < a.length; ) {
if (a[i].name.match(/^on/i)) {
el.removeAttribute(a[i].name);
} else {
++i;
}
}
// recursively test the children
var child = el.firstChild;
while (child) {
cleanHandlers(child);
child = child.nextSibling;
}
}
cleanHandlers(document.body);
working demo at http://jsfiddle.net/alnitak/dqV5k/
unbind() doesn't work because you are using inline onclick event handler. If you were binding your click event using jquery/javascript the you can unbind the event using unbind(). To remove any inline events you can just use removeAttr('onclick')
$('a').click(function(){ //<-- bound using script
alert('clicked');
$('a').unbind(); //<-- will unbind all events that aren't inline on all anchors once one link is clicked
});
http://jsfiddle.net/LZgjF/1/
I ended up with this solution, which removes all events on any item.
function RemoveEvilScripts(){
var myDiv = $('<div>').html('testing this Do it! out');
//remove all the different types of events
$(myDiv)
.find('*')
.removeAttr('onload')
.removeAttr('onunload')
.removeAttr('onblur')
.removeAttr('onchange')
.removeAttr('onfocus')
.removeAttr('onreset')
.removeAttr('onselect')
.removeAttr('onsubmit')
.removeAttr('onabort')
.removeAttr('onkeydown')
.removeAttr('onkeypress')
.removeAttr('onkeyup')
.removeAttr('onclick')
.removeAttr('ondblclick')
.removeAttr('onmousedown')
.removeAttr('onmousemove')
.removeAttr('onmouseout')
.removeAttr('onmouseover')
.removeAttr('onmouseup');
return $(myDiv).html();
}
If for example I have the next event:
document.getElementById('TagSearchInput').onkeyup = function(e)
{
//Code...
}
Inside the event, there is a condition where I recreate the element (TagSearchInput). How can I refresh the event selector, from within the event?
OK, ignoring any questions about why you'd be recreating the input...
Rather than using an anonymous function try something like this:
function TSIKeyupHandler(e)
{
//Code...
// within your condition where you want to re-attach the handler
document.getElementById('TagSearchInput').onkeyup = TSIKeyupHandler;
}
document.getElementById('TagSearchInput').onkeyup = TSIKeyupHandler;
(Optionally put all of the above inside an immediately-invoked-anonymous-function if you want to keep the TSIKeyupHandler() function out of the global scope.)
Once again I've inherited someone else's system which is a bit of a mess. I'm currently working with an old ASP.NET (VB) webforms app that spits JavaScript onto the client via the server - not nice! I'm also limited on what I can edit in regards to the application.
I have a scenario where I have a function that does a simple exercise but would also need to know what item was clicked to executed the function, as the function can be executed from a number of places within the system...
Say I had a function like so...
function updateMyDiv() {
$('#div1').hide();
$('#div2').hide();
$('#div13').show();
}
how could I get the ID (for example) of the HTML element that was clicked to execute this?
Something like:
function updateMyDiv() {
alert(htmlelement.id) // need to raise the ID of what was clicked,
$('#div1').hide();
$('#div2').hide();
$('#div13').show();
}
I can expand on this if neccessary, do I need to pass this as an arguement?
The this keyword references the element that fired the event. Either:
<element onClick="doSomething(this);">
or
element.onclick = function() {
alert(this.id);
}
Bind your click events with jQuery and then reference $(this)
$('.myDivClass').live('click', function () {
updateMyDiv(this);
});
var updateMyDiv = function (that) {
alert(that.id);
// save the world
};
You don't need to pass "this", it is assigned automatically. You can do something like this:
$('div').click(function(){
alert($(this).attr('id'));
})
Attach the function as the elements event handler is one way,
$(htmlelement).click(updateMyDiv);
If you are working with an already generated event, you can call getElementByPoint and pass in the events x,y coords to get the element the mouse was hovering over.
$('.something').click(function(){
alert($(this).attr('id'));
});
You would need to pass it the event.target variable.
$("element").click(function(event) {
updateMyDiv($(event.target));
});
function updateMyDiv(target) {
alert(target.prop("id"));
}
Where is your .click event handler? Wherever it is, the variable this inside of it will be the element clicked upon.
If you have an onclick attribute firing your function, change it to
<tag attribute="value" onclick="updateMyDiv(this)">
and change the JavaScript to
function updateMyDiv(obj) {
alert(obj.getAttribute('id')) // need to raise the ID of what was clicked,
$('#div1').hide();
$('#div2').hide();
$('#div13').show();
}
use the .attr('id') method and specify the id which will return what you need.
var dayNumberCell = doc.createElement('td');
dayNumberCell.className = 'days_link';
dayNumberCell.setAttribute('onclick', function(scope) {
var bindScope = function() {
scope.changeDate(this, this.id);
scope.returnDate(scope.month, scope.year);
};
return bindScope;
}(this));
The above code generates tds onclick event listener. and the generated code looks like
<td class="days_link" onclick="function () {
scope.changeDate(this, this.id);
scope.returnDate(scope.month, scope.year);
}">15</td>
By clicking on TD I get syntax error message.
How should I write my function that the specified code executes and also have no syntax error.
Thanks in advance.
You put your function definition inside a string literal. It's expecting code and all it has is text.
You should rewrite your onclick handler as follows:
dayNumberCell.onclick = function(e) {
var target = e.target || e.srcElement;
target.changeDate(target, target.id);
target.returnDate(target.month, target.year);
return false;
};
I don't understand why you would try to set the inline click handler from an external js file. You took the right step to remove inline click handlers from your html, but when you set the click handler from an external script, you should not be setting the onclick attribute.
In addition to the way I highlighted, you could use the w3c and microsoft event handlers so that you can attach multiple onclick events to the same element. However, this is a more complicated approach since different browsers handle it differently. This will suffice as long as you don't plan to have other onclick handlers attached to the same cell.
<td class="days_link" onclick="function () {
scope.changeDate(this, this.id);
scope.returnDate(scope.month, scope.year);}">15</td>
Have you tried outside the function?
<td class="days_link" onclick="scope.changeDate(this, this.id);scope.returnDate(scope.month, scope.year);">15</td>
if that don't work, try it on your javascript file, and there, yes, with a function.
Perhaps you would prefer not to use any javascript libraries, but I would highly recommend using the YUI Event utility for this.
Dustin Diaz has a great article that explains how it would simplify this for you.
http://www.dustindiaz.com/yahoo-event-utility/