Transverse Html Elements Till a Specifc Attribute (id) using Jquery - html

I am using Jquery 1.7.2.
I want to transverse Html Elements Till a Specifc Attribute (id) using Jquery on
mouse over on any html element in my page.
we have parents() function but problem is how to select stop on the parent element which has id attribute
$("*", document.body).click(function (e) {
e.stopPropagation();
var domEl = $(this).get(0);
var parentEls = $(domEl).parents()
.map(function () {
return this.tagName;
})
.get().join(", ");
$("b").append("" + parentEls + "");
});
this is code but i am getting all element till root
but i want to stop on a closet elements which has attribute id in the tag
Please help me out .

Just use closest:
$(this).closest('#the-id');
Unless your'e just looking for the closest one that has any id attribute, which would be:
$(this).closest('[id]');
Edit: after seeing your updated question, this should be what you want:
$(document).click(function(e) {
e.preventDefault();
var parents = $(e.target).parentsUntil('[id]')
.map(function() { return this.tagName; }).get().join(',');
console.log(parents);
});
Note that this approach accomplishes what you want without selecting and binding click events to every node in the DOM, which is a pretty heavy handed approach.
Edit (again): looks like maybe you wanted to include the tag with the id attribute on it (the above solution is everything up to, but not including that tag). To do this, the solution is pretty similar:
$(document).click(function(e) {
e.preventDefault();
var $parents = $(e.target).parentsUntil('[id]');
var tagNames = $parents.add($parents.parent())
.map(function() { return this.tagName; }).get().join(',');
console.log(tagNames);
});

It looks like you want to map the hierarchy from the clicked element up to the document root. In that case, you can apply parents() to event.target:
$(document).click(function(e) {
e.preventDefault();
var parentEls = $(e.target).parents().map(function() {
return this.tagName;
}).get().join(", ");
});
Note that, as jmar777, you should also change your selector: "*" adds an event handler to all the elements, which is probably not what you want. Bind a single handler to document instead to take advantage of event bubbling.

Related

How to continue jQuery Function

I am using the following code to change href links in a page to a new link by using their id.
This is what I'm using to find the href and add the id to it;
$( document ).ready(function() {
$('a[href$="/truck-bed-covers/camper-tops"]').attr('id', 'camper1');
});
And this is what I'm using to change the link.
$(document).ready(function () {
$("#camper1").attr("href", "../camper-tops");
});
It works great. Except it doesn't continue on the rest of the page. It only changes one link and then it's done. How do I continue until there is no more links to change?
ID has to be unique, else JavaScript works with the first one only.
$(document).ready(function() {
$('a[href$="/truck-bed-covers/camper-tops"]').each(function(){
$(this).attr("href", "../camper-tops");
});
});
But I don't think this is the right way. You should find place where you create incorrect links and repair it there (in PHP/DB or where links came from).
At a guess, you're adding the ID so you can refer to the element in the second line, but you don't need to. Once you have an element you can work on it.
You can select all links with something like $('a[href]') (all links with an href attribute) and then iterate over all of them with jQuery's each function. Something like
$(function(){ // shorthand for $(document).ready()
$('a[href]').each(function(index, element){
// work on each element here
var $el = $(element);
$el.attr('href', $el.attr('href').replace(/*whatever you want to do here */);
});
});

detecting and hiding dynamically creating div after a specific seconds (not onclick)

i have a dynamically generating div which is not in the time of loading. It is generating later in the document. So how can i target that div and hide it after specific time. The div is as follows:
<div class="message-sent">Your Message has been sent</div>
Important: I refer so many articles but everyone is talking about 'onclick'. I don't want click event. I just want hide this div when it is appearing in the docuemnt. Thanks in advance!
you can add a style display:none.
you can add the style after time out (3000ms) like so:
setTimeout(function(){
document.getElementsByClassName("message-sent")[0].style.display="none";
}, 3000);
note: it is better if you use an id instead of a class to identify your div.
You should try looking into the setTimeout function.
Also if that div is the only member of the DOM-tree that has that class, use an ID. It's better IMO.
Anyway, assuming you want to hide every member of the message-sent-class,
it goes something like this:
setTimeout(function(){
$('.message-sent').hide();
}, 2000)
In which the 2000is the variable that indicates the time (milliseconds)
You can try DOMNodeInserted,
$(document).bind('DOMNodeInserted', function(event) {
var element = document.getElementsByClassName("message-sent"); // get all elements with class message-sent
var lastchild = element[element.length - 1]; // get the last one (others are hidden)
if(lastchild != null){
lastchild.style.visibility = 'hidden'; // set visibility to hidden
}
});
Working demo
Hope helps,

jQuery livequery plug equivalent in jQuery 1.7+

Is there the equivalent of the jQuery livequery plugin for jQuery 1.7+ ?
I'm trying to dynamically bind events, reading the events a DOM element should bind on based on data-* elements.
Test 1
Test 2
.. etc ..
I want to bind all elements with class .js-test but only on the events listed in their data-events attribute.
jQuery.on/live/bind/delegate all require the events to be passed in as params.
This is find for DOM elements that exist on the page when document.ready, however as I update the DOM (AJAX, JS, etc.) I want any new elements with class .js-test to have its events bound as well.
The livequery plugin (which is old, from jQuery 1.3 times) seems to allow this, as it simple requires a selector and a function to run against anything that matches the selector.
As of jQuery 1.7 the on method, supercedes the live method. While it doesn't have an easy method of passing in or matching selectors like you describe, it is possible to accomplish this by passing in the dynamic value of data-events in place of the event type, as long as the data-event value matches that event.
However, since the argument passed into the on method's event parameter -- the first parameter -- is taken from each data-events attribute, from each element in the set of matched elements, we must loop through the collection of matched elements so that we access each elements' individual data-events attribute value separately:
$('.js-test').each(function() {
$(this).on( $(this).attr("data-events"), function() {
// event pulled from data-events attribute
alert("hello - this event was triggered by the " + $(this).attr("data-events") + " action.");
});
});
I want all events to be mapped to the same function, but have different events trigger the function call for different DOM elements.
Since you want to map all of the events to a single function, this solution meets your specific requirements, and solves your problem.
However, should your requirements change and you find you need to map a collection of function events to match each event type, this should get you started:
var eventFnArray = [];
eventFnArray["click"] = function() {
alert("click event fired - do xyz here");
// do xyz
};
eventFnArray["mouseover"] = function() {
alert("mouseover fired - do abc here");
// do abc
};
$('.js-test').each( (function(fn) {
return function() {
$(this).on( $(this).attr("data-events"), function() {
alert("hello - this is the " + $(this).attr("data-events") + " event");
// delegate to the correct event handler based on the event type
fn[ $(this).attr("data-events") ]();
});
}
})(eventFnArray)); // pass function array into closure
UPDATE:
This has been tested and does indeed work for new elements added to the div#container. The problem was in the way the on method functions. The delegating nature of on only works if the parent element is included in the selector, and only if a selector is passed into the second parameter, which filters the target elements by data-events attribute:
HTML:
<div id="container">
Test 1
Test 2
</div>
JavaScript:
$(document).ready(function() {
$('.js-test').each(function() {
var _that = this;
alert($(_that).attr("data-events"));
$(this).parent().on(
$(_that).attr("data-events"),
'.js-test[data-events="'+ $(_that).attr("data-events") +'"]',
function() {
// event pulled from data-events attribute
alert("hello - this event was triggered by the " + $(_that).attr("data-events") + " action.");
}
);
}
);
});
Additionally, use the following jQuery to add an item to the container to test it:
$('#container')
.append("<a href='#' class='js-test' data-events='mouseover'>Test 3</a>");
Try it out:
Here is a jsfiddle that demonstrates the tested and working functionality.

Why does not jQuery.live function work with static elements?

I have a dynamic HTML table, where I can add and remove rows.
Each row contains a button that has a class removeRow.
In my JavaScript, I have:
$('button.removeRow').live("click", function () {
var row = $(this).parents('tr')
row.remove();
return false;
});
The problem is that it works for all buttons that belong to rows that were inserted after the page was loaded (by clicking on 'Add row' button).
It works for existing buttons, only if I change the above code to (but then it does not work for dynamically added rows):
$('button.removeRow').click(function () {
var row = $(this).parents('tr')
row.remove();
return false;
});
I think that the live function should work for both, so can you point me into the right direction? Where can it go wrong?
OK I found a bug today. Somewhere in my code I had:
$('input[type=submit], button').click(function () {
return false;
});
I wanted it to work with the submit button, so it would not submit the form on click. I do not remember why I put button there. Anyways, because of that my static button clicks were attached this event, while dynamically created ones were not. Therefore live 'click' worked for dynamic buttons. Stupid mistake...
Hacky solution: Do both
$('button.removeRow').live("click", function () {
var row = $(this).parents('tr')
row.remove();
return false;
});
and
$('button.removeRow').click(function () {
var row = $(this).parents('tr')
row.remove();
return false;
});
It would be helpful if you posted some example HTML as well as the code responsible for inserting new rows, though.
Maybe something is going wrong if other tr elements are matched by your .parents() selector. Try .closest():
$('button.removeRow').live("click", function(){
$(this).closest('tr').remove();
return false;
});
The live should work for both dynamic and pre-rendered elements.
I'd start by working out if that content really exists before that jQuery is run...Try outputting the result of the following somewhere, or use the debugger keyword, or even the dreaded alert:
$('button.removeRow').length
// The rest of your click handler definition...

How to do callback + update div tag in javascript

I have an ASP.NET MVC application with pages where the content is loaded into divs from client via JavaScript/jQuery/JSON. The loaded content contains a-tags with references to a function that updates server side values, then redirects to reload of entire page even though.
I wish to replace the a-tags with 'something' to still call a server-side function, then reload the div only.
What is the 'right' way of doing this?
All comments welcome.
This is as far as I got so far. getResponseCell() returns a td-tag filled with a-tag.
I've mangled Glens suggestion into the .click() addition, but it just calls the onClickedEvent...
Code sample:
onClickedEvent=function()
{
return false;
}
getResponseCell=function(label, action, eventId)
{
tmpSubSubCell=document.createElement("td");
link = document.createElement("A");
link.appendChild( document.createTextNode( label));
link.setAttribute("href", "/EventResponse/"+ action + "/" + eventId);
//link.setAttribute("href", "#divContentsEventList");
//link.setAttribute("onclick", "onClickedEvent(); return false;");
link.setAttribute("className", "eventResponseLink");
link.click(onClickedEvent());
// link=jQuery("<A>Kommer<A/>").attr("href", "/EventResponse/"+ action + "/" + eventId).addClass("eventResponseLink");
// link.appendTo(tmpSubSubCell);
tmpSubSubCell.appendChild(link);
return tmpSubSubCell;
}
And the solution that worked for me looks like this:
onClickedEvent=function(event, actionLink)
{
event.preventDefault();
$("eventListDisplay").load(actionLink);
refreshEventList();
return false;
}
getResponseCell=function(label, action, eventId)
{
tmpSubSubCell=document.createElement("td");
link = document.createElement("A");
link.setAttribute("id",action + eventId);
link.appendChild( document.createTextNode( label));
actionLink = "/EventResponse/"+ action + "/" + eventId;
link.setAttribute("href", actionLink);
className = "eventResponseLink"+ action + eventId;
link.setAttribute("className", className);
$('a.'+className).live('click', function (event)
{
onClickedEvent(event,$(this).attr('href'));
});
tmpSubSubCell.appendChild(link);
return tmpSubSubCell;
}
Without really seeing more information.....
If you're a's are being added to the DOM after the initial page load, you cannot use the usual click() or bind() methods in jQuery; this is because these methods only bind the events to those elements that are registered in the DOM at the time the methods are called. live() on the other hand, will register the event for all current, and future elements (using the event bubbling mechanism in Javascript).
$(document).ready(function () {
$('a.eventResponseLink').live('click', function (event) {
var self = $(this);
self.closest('div').load('/callYourServerSideFunction.asp?clickedHref=' + self.attr('href'));
event.preventDefault();
});
});
We're using event.preventDefault() to prevent the default action of the a-tag being executed; e.g. reloading or changing page.
Edit: The issue won't be caused by that. That's the power of jQuery; being able to bind the same event to multiple elements. Check your HTML; maybe you're missing a closing </a> somewhere? Maybe your binding the event in a location that gets called multiple times? Each time .live() gets called, it will add ANOTHER event handler to all matched elements. It only needs to be bound once on page load.
jQuery provides loads of way for you to select the elements; check out the list. Looking at your link variable, it looks like all your links have a href starting with /EventResponse/; so you can use $('a[href^=/EventResponse/]') as the selector instead.
We need code to give you a proper answer, but the following code will catch the click of an a-tag, and reload the div that it's inside:
$(document).ready(function() {
$("a").click(function() {
//call server-side function
var parentDiv = $(this).parents("div:first");
$(parentDiv).load("getContentOfThisDiv.asp?id=" + $(parentDiv).attr("id"));
});
});
In the above code, when a link is clicked, the div that this the link is inside will be loaded with the response of the call to the asp file. The id of the div is sent to the file as a parameter.