How to get HTML element from event in jquery? - javascript

In a jQuery function I am getting event on form's element click event. Now I want to get its html. How it is possible ?
For Example:
function(event, ID, fileObj, response, data) {
alert( $(event.target) ); // output: [object Object]
alert( event.target ); // output: [object HTMLInputElement]
alert( $(event.target).html() ); // output: (nothing)
}
I want to get form object who's element is clicked through event
Thanks

You can try event.target.outerHTML, however I'm not sure how well supported it is across all browsers. A more convoluted but sure to work solution would be to wrap the element in another element, then take the html of the parent element:
$('<div/>').html($(event.target).clone()).html();

If your event is a click you can bind it using the click() method from jQuery. Use this to reach your element, like the code below:
$('#id').click(function(event){
console.log($(this));
});

Most elegant solution I found is to simply use the properties on the event target.
Here is an example how to detect the event source html tag.
This example assumes you have bound a list item click event of unordered list with CSS class name myUnorderedList but you want to disable the default action if an anchor tag is clicked within the list item:
$('ul.myUnorderedList').on('click', 'li', function(event){
console.log('tagName: '+ event.target.tagName); //output: "a"
console.log('localName: '+ event.target.localName);//output: "a"
console.log('nodeName: '+ event.target.nodeName); //output: "A"
if(event.target.tagName == 'a')
return; // don't do anything...
// your code if hyperlink is not clicked
});

Related

Printing the full HTML of the DOM element that triggered an eventListener in Javascript

I am trying to print out the full HTML of the DOM element with limited success. I would like to know if there's a helper in JavaScript that's intended to do just that.
this.div.click( function(e) {
alert(e.target);
alert(e.target.tagName);
alert(JSON.stringify($(e.target).parent()));
});
I am expecting to get something like:
<div class="gameActivator AnyItem-Off-selector UI-Widget UI-Content"><span class="content widget-inner"><button class="activateButton"></button></span></div>
Use currentTarget to get the element on which the event listener was originally attached. Then you can read all the HTML of that element with outerHTML.
this.div.click( function(e) {
console.log(e.currentTarget.outerHTML);
});
A live demo at jsFiddle.
You can use this.outerHTML. Inside a jQuery event handler this is the current element
this.div.click( function(e) {
console.log(this.outerHTML);
});
Use innerHTML or outerHTML, depending on wether you want to include the given element in the returned HTML.
this.div.click( function(e) {
console.log( this.innerHTML );
console.log( this.outerHTML );
});
In jQuery it would be just html()
console.log( $(this).html() );

How can I return a href link to it's default behavior after using e.preventDefault();?

I updated my code and rephrased my question:
I am trying to create the following condition. When a link with an empty href attribute (for example href="") is clicked, a modal is launched and the default behavior of that link is prevented..
But when the href attribute contains a value (href="www.something.com") I would like for the link to work as it normally does using its default behavior.
For some reason my code isn't working. Any help is appreciated.
// Semicolon (;) to ensure closing of earlier scripting
// Encapsulation
// $ is assigned to jQuery
;(function($) {
// DOM Ready
$(function() {
// Binding a click event
// From jQuery v.1.7.0 use .on() instead of .bind()
$('.launch').bind('click', function(e) {
var attrId = $(this).attr('attrId');
if( $('.launch').attr('href') == '') {
// Prevents the default action to be triggered.
e.preventDefault();
// Triggering bPopup when click event is fired
$('div[attrId="' + attrId+'"]').bPopup({
//position: ['auto', 'auto'], //x, y
appendTo: 'body'
});
} else {
$(this).removeAttribute('attrId');
return true;
}
});
});
})(jQuery);
Your jQuery is... very wrong. $('href').attr('') is getting the empty attribute from an element <href>... Did you mean:
if( $(this).attr('href') == '')
A few things: event is undefined, as your event object is simply called e. Secondly, e.stopPropagation(); will not do what you want. stopPropagation simply prevents parent events from firing (eg: clicking a <td> will also fire click on the containing <tr> unless stopped).
Try just replacing your else statement with
return true;
Also your jQuery is incorrect (as stated in the other answer here).
This answer may help as well:
How to trigger an event after using event.preventDefault()
Good luck!

How can I show a DIV by it's attribute value using Jquery

I am working with a Jquery plugin and I would like to trigger the modal (div) by calling it's value instead of calling it's ID name.
So if the attribute value is "554" meaning attrId="554" I will display the modal with the matching "554" attribute. Please keep in mind that the attribute value could be a variable.
My JSFiddle Code Example is here
;(function($) {
// DOM Ready
$(function() {
// Binding a click event
// From jQuery v.1.7.0 use .on() instead of .bind()
$('#my-button').bind('click', function(e) {
// Prevents the default action to be triggered.
e.preventDefault();
// Triggering bPopup when click event is fired
$('#element_to_pop_up').bPopup();
});
});
})(jQuery);
Any help is appreciated. Thanks so much
You can use an attribute equals selector: [attribute="value"]
If your popup div has an attribute like this:
<div id="element_to_pop_up" attrId="554">
<a class="b-close">x</a>
Content of popup
</div>
You can use the following:
var x = '554';
$('div[attrId="' + x + '"]').bPopup();
jsfiddle
Ultimately it needs a unique selector unless you are okay with triggering multiple modals. One way to do it is to use the jQuery each function, and check each div for the matching attribute.
$( "div" ).each(function() {
var criteria = 'example_criteria';
if ($( this ).attr( "attributename" ) == criteria)
{
$(this).bPopup();
}
});

How to get the jQuery `$(this)` id?

How can I get the id of the element that triggered the jQuery .change() function?
The function itself works properly, but I need a specific action for a selector with id="next".
$("select").change(function() {
[...snip....]
alert( $(this).attr('id') ); // <---- not working
}
Any ideas why the alert above isn't working?
this is the DOM element on which the event was hooked. this.id is its ID. No need to wrap it in a jQuery instance to get it, the id property reflects the attribute reliably on all browsers.
$("select").change(function() {
alert("Changed: " + this.id);
}
Live example
You're not doing this in your code sample, but if you were watching a container with several form elements, that would give you the ID of the container. If you want the ID of the element that triggered the event, you could get that from the event object's target property:
$("#container").change(function(event) {
alert("Field " + event.target.id + " changed");
});
Live example
(jQuery ensures that the change event bubbles, even on IE where it doesn't natively.)
Do you mean that for a select element with an id of "next" you need to perform some specific script?
$("#next").change(function(){
//enter code here
});

Retrieving previously focused element

I would like to find out, in Javascript, which previous element had focus as opposed to the current focus. I've been looking through the DOM and haven't found what I need, yet. Is there a way to do this any help would be much appreciated
Each time an element is focused, you'd have to store which one it was. Then when another element is focused, you could retrieve the variable for the previous focused element.
So basically, your single focus handler would do 2 things:
Check if previousFocus is defined. If it is, retrieve it.
Set previousFocus to the currently focused element.
Here is a quick demo with jQuery (you can use raw JS too... just fewer lines w jQuery, so it's easier to understand imo):
// create an anonymous function that we call immediately
// this will hold our previous focus variable, so we don't
// clutter the global scope
(function() {
// the variable to hold the previously focused element
var prevFocus;
// our single focus event handler
$("input").focus(function() {
// let's check if the previous focus has already been defined
if (typeof prevFocus !== "undefined") {
// we do something with the previously focused element
$("#prev").html(prevFocus.val());
}
// AFTER we check upon the previously focused element
// we (re)define the previously focused element
// for use in the next focus event
prevFocus = $(this);
});
})();
working jsFiddle
Just found this question while solving the exact same problem and realised it was so old the jQuery world has moved on a bit :)
This should provide a more effective version of Peter Ajtais code, as it will use only a single delegated event handler (not one per input element).
// prime with empty jQuery object
window.prevFocus = $();
// Catch any bubbling focusin events (focus does not bubble)
$(document).on('focusin', ':input', function () {
// Test: Show the previous value/text so we know it works!
$("#prev").html(prevFocus.val() || prevFocus.text());
// Save the previously clicked value for later
window.prevFocus = $(this);
});
JSFiddle: http://jsfiddle.net/TrueBlueAussie/EzPfK/80/
Notes:
Uses $() to create an empty jQuery object (allows it to be used immediately).
As this one uses the jQuery :input selector it works with select & button elements as well as inputs.
It does not need a DOM ready handler as document is always present.
As the previously focused control is required "elsehere" is is simply stored on window for global use, so it does not need an IIFE function wrapper.
Well depending on what else your page is doing, it could be tricky, but for starters you could have a "blur" event handler attached to the <body> element that just stashes the event target.
To me this seems a slight improvement on Gone Coding's answer:
window.currFocus = document;
// Catch focusin
$(window).on( 'focusin', function () {
window.prevFocus = window.currFocus;
console.log( '£ prevFocus set to:');
console.log( window.currFocus );
window.currFocus = document.activeElement;
});
... there's no stipulation in the question that we're talking exclusively about INPUTs here: it says "previous elements". The above code would also include recording focus of things like BUTTONs, or anything capable of getting focus.
document.getElementById('message-text-area').addEventListener('focus',
event => console.log('FOCUS!')
);
event.relatedTarget has all the data about the previously focused element.
See also https://developer.mozilla.org/en-US/docs/Web/API/Event/Comparison_of_Event_Targets
Here is a slightly different approach which watches both focusin and focusout, in this case to prevent focus to a class of inputs:
<input type="text" name="xyz" value="abc" readonly class="nofocus">
<script>
$(function() {
var leaving = $(document);
$(document).on('focusout', function(e) {
leaving = e.target;
});
$( '.nofocus' ).on('focusin', function(e) {
leaving.focus();
});
$( '.nofocus' ).attr('tabIndex', -1);
});
</script>
Setting tabIndex prevents keyboard users from "getting stuck".

Categories

Resources