Showing posts with label Event Target. Show all posts
Showing posts with label Event Target. Show all posts

Friday, 20 July 2012

How to find event target using jQuery?

This can be done using event.target property. It returns a reference to the DOM element that initiated the event. t is often useful to compare event.target to this in order to determine if the event is being handled due to event bubbling. This property is very useful in event delegation, when events bubble.

Example: Implements a simple event delegation: The click handler is added to an unordered list, and the children of its li children are hidden. Clicking one of the li children toggles (see toggle()) their children.


<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  
<ul>
  <li>item 1
    <ul>
      <li>sub item 1-a</li>
      <li>sub item 1-b</li>
    </ul>
  </li>
  <li>item 2
    <ul>
      <li>sub item 2-a</li>
      <li>sub item 2-b</li>
    </ul>
  </li>  
</ul>

<script>

function handler(event) {

var $target = $(event.target);

  if( $target.is("li") ) {
    $target.children().toggle();
  }
}

$("ul").click(handler).find("ul").hide();

</script>

</body>
</html>


Thursday, 2 December 2010

Using jQuery to modify QueryString

I recenlty worked on a requirement where I have to modify the querystring of all the links in a page before the actual request is made from the browser, i.e. when a link is clicked. There may be better ways to do this but this is how I implemented it using jQuery.


$(document).ready(function() {
$('a').click(function(event) {

var $a = $(event.target);

if ($a.is('a')) { //if the event is triggered by an <a> tag

//append refid querystring to href
if it is not an external url and it refers to
an ASPX page and does not already contain
refid in querystring

var appendrefid =
$a.attr("href").toLowerCase().indexOf("http://") == -1
&&
$a.attr("href").toLowerCase().indexOf("https://") == -1
&&
$a.attr("href").toLowerCase().indexOf(".aspx") != -1
&&
$a.attr("href").toLowerCase().indexOf("refid=") == -1;

if (appendrefid) {

event.preventDefault();
location.href = $a.attr("href") + "?refid=" + GetQStringVal("refid");
}
}
});
});

/* function to read value of the given key, x, from querystring */
function GetQStringVal(x) {

var a = location.search.substring(1); var b = a.split("&");

for (var i = 0; i < b.length; i++) {
var c = b[i].split("=");
if (c[0].toLowerCase() == x.toLowerCase()) { return c[1]; }
}

return "";
}


Here the main page, where the content is coming from the database, is always requested with refid in the querystring and the above script reads the refid from the original request and appends it to the newly requested page when the link is clicked.