jQuery: How to find an element inside of hashchange event handler? - javascript

A web-page has some links:
example-1
example-2
example-n
Clicking any on them it runs an event of hashchange and we going to handle it:
$(window).on('hashchange', function(event){
// Is it possible (inside this handler) to find out which of a.link was clicked?
});
Or, is there another way to do it?

While I believe adding click listeners to the actual links would be best, you could also search for the element that would have changed the hash as such:
$(window).on('hashchange', function(event){
$('a[href$='+window.location.hash+']').action();
});

I think you could use onclick as an attribute in the tag or you could use the .click() event through jQuery. I think that will accomplish the same as the window on hashchange.

event.target will hold which element triggered the event.
I can't check at the moment, but I believe that this also binds.

try this:
$(window).on('hashchange', function(event){
var hash = location.hash;
var $this = $(hash);
alert($this.html());
});

Related

how can we over write the keypress event in jquery

Suppose I have a jQuery file where I have defined a key press action. And in my aspx page I want to override that key press action.
How can I achieve that?
$('#item').unbind('keypress');
var input = '#txtId'; //txtid is ur textbox,textarea id
$(input).keypress(function(e) {
e.preventDefault();
});
Imagine you have this scenario:
var handler = function(){ ... }
$('body').on('keypress', ':input', handler);
Then you can remove that specific handler - with no impact on the others - with the following:
$('body').off('keypress', ':input', handler);
To remove ALL keypress handlers just call it without passing the handler
$('body').off('keypress', ':input');
To remove all event handlers from a specific element just use it without arguments
$(':input').off();
Instead if you want simply prevent the default behaviour, just use the preventDefault function
$('body').on('keypress', ':input', function(e){
e.preventDefault();
...
});
In case instead you wat to use your handler just once there's the once function in jQuery that will bind your handler and unbind it at the end of the execution;
Sorry for the long answer but your question wasn't completely clear to me.
Documentation link for jQuery off()

jquery "on" event not firing for click event?

For some reason I can't get my "on" event to fire for a click event. Here is what the call and HTML look like:
HTML:
<a class="cmt-replies-show" href="javascript:void(0)" id="cmt-count" style="">
<span>View All</span>
</a>
jQuery:
$('.cmt-replies-show').on("click", function(e) {
e.preventDefault();
alert("Clicked");
});
Any idea what I'm missing?
The most probable reason is that the element isn't in the DOM when you bind the event.
If you add the element dynamically, you may do this :
$(document.body).on("click", '.cmt-replies-show', function(e) {
If your script is included in the page before the element, you may either move your script at the end of the body or call your code on ready event :
$(function(){
$('.cmt-replies-show').on("click", function(e) {
e.preventDefault();
alert("Clicked");
});
});
What Paul said - make sure you bind the event after the DOM is ready.
FYI if you're directly targeting an element with 'on', you can just use $('a').click(function(){...}); . 'On' is more useful if you want to delegate events like so:
$('#container').on('click','a',function(){
});
You probably define the div after the script has executed.
Wrap it in $(document).ready(function() { .... }); to ensure it executes after the full DOM is available.
If you are trying to access element dynamically injected into DOM, you should use the following syntax:
$(document).on('click', '.cmt-replies-show', function(e) {
// your code goes here
});
The document can be replaced with each parent which is available when document is ready.
I understand the reason to be dynamic injection of this link on the page. Your DOM was already in ready state and all the functions were read when this part of code is injected.
When you inject the HTML, bind the element with click function.
Using live() should solve your purpose -
$('#yourLink').live('click', function(){
//Your logic here
});

Binding jQuery events before DOM insertion

My problem is that I have to create event listeners on certain DOM elements before I insert them into the dom.
Now generally this is quite easy like so:
var button = $('<button>Click Me</button>');
button.on('click', function(){ alert('clicked'); });
$('body').append(button);
However, the problem is that I need to wrap the button in other html as in this example:
http://jsfiddle.net/a8xjJ/
The Event Listener breaks if I mix the button object with a string of html.
That's when the Event Listener looses touch with the object, quite logically.
My problem is that I need to use strings of html, that's a constraint of the project. Maybe there is a way in which I can use the dom selector on a string? Or maybe you can think of another way of making the above fiddle work.
You can bind the dynamic elements by using .delegate() function of JQuery.
I have updated your fiddle to this.
var button = $('<button>Click Me</button>');
var html = '<form>' + button.clone().wrap('<div/>').parent().html() + '</form>';
$('div').append(html);
$(document).delegate(button,'click', function(e){
e.preventDefault();
alert('Clicked');
});
You may also use .on() to bind the events on dynamic elements.
$(document).on('click', button, function(e){
e.preventDefault();
alert('Clicked');
});
Notice that this method takes event as its first parameter.
If you started to work with objects, try not to use their string representation (it outputs the shell only but not the events and other data). One possible solution of you problem:
$("<button>Click Me</button>").on("click", function(e) {
e.preventDefault();
alert("Clicked");
}).wrap("<form><div></div></form>").closest("form").appendTo("div");
DEMO: http://jsfiddle.net/a8xjJ/2/

In Javascript (jquery), is there a way to detect when the page anchor changes?

Basically, I want to have links throughout the page that change the anchor -- the part of the URL after a # symbol. When that part of the URL changes, the JavaScript should respond.
I could add an onclick method to every link, but is there a better way?
That's not an anchor, it's the hash?
$(window).on('hashchange', function() {
alert('My fracking hash changed to : '+document.location.hash);
});
$(window).bind('hashchange', function() {
// code here
});
think that should do it
In jQuery you don't need to add onclick events to all links individual. With a selector like $('a') you could add an event to all of your links at once.
$('a').click(function(){
// code here
});
Inside this event you can use the $(this) object to get the href.
But I suggest that the other answers show you a more elegant way for solving this problem.
you can add a delegate to a,
$(elements).on(events, selector, data, handler);
the difference is it won't add "onClick" to every a element, but it will catch the "onClick" event of a
First of all you have to pick the element.
For example var links = $("a");
Then you add the jquery function .click()
Try this
Store window.location.hash on a global variable, say, currentHash
Create a function to check window.location.hash !== currentHash
If the check fails set currentHash = window.location.hash
Execute this function using setInterval on DOMReady
Sammy.js is your friend here. I've used it on a SPA I'm working on and I love it!

Auto click to dynamically added link

I want to auto click to the dynamically added link. Here is my script
document.write("<a id='tikla' href='http://www.example.org'>tikla</a>");
$('#tikla').click();
However it doesn't work, because of the link is dynamically added object. What is the correct way to do that ?
What are you trying to do? It looks like you just want to go to the href location?
If that's the case you can just go
window.location.href = 'http://www.example.org';
You need to add click handler before you trigger click event
Live Demo
document.write("<a id='tikla' href='http://www.example.org'>tikla</a>");
$('#tikla').click(function(){
alert("clicked");
});
$('#tikla').click();
For binding events for elements added dynamcially jQuery provides event delegation using jQuery on().
Delegated events
Delegated events have the advantage that they can process events from
descendant elements that are added to the document at a later time. By
picking an element that is guaranteed to be present at the time the
delegated event handler is attached, you can use delegated events to
avoid the need to frequently attach and remove event handlers.
$( "#staticparent" ).on( "click", "#tikla", function() {
alert("clicked");
});
You can try it like this also...
document.write("<a id='tikla' href='http://www.example.org'>tikla</a>");
window.location.href = $('#tikla').attr('href');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
Use
$('#tikla').get(0).click();
Because, you need to emulate the dom element click.
$('#tikla').click(); will trigger the jquery click event binded to that anchor element. In your case there is nothing binded to the anchor element.
Fiddle
Try this,
$("<a id='tikla' href='http://www.example.org'>tikla</a>")
.appendTo('body') // appendto body
.get(0).click(); // triggering click to itself
$("<a id='tikla' href='http://www.example.org'>tikla</a>")
.appendTo('body')
.get(0).click();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
var myLink = document.getElementById('tikla');
myLink.click();
Thanks for all you guys, but none worked in Internet Explorer. I found this simple javascript works in all of the browsers.

Categories

Resources