Analyze JS syntax - javascript

I am trying to analyze a line of code written by someone else. Specifically I want to find the Javascript code that is called when the below link is clicked....
<a href="#subtabs_and_searchbar"
id="finish_counting"
onclick="$('#finish_counting').click();">
<span>Submit Answer</span>
</a>
But as you can see they do not have the actual Javascript function name inside the onClick event listener. Can you please help me understand what is there?
Also is this syntax pure Javascript or is there something else there? Jquery perhaps?

Specifically I want to find the Javascript code that is called when
the below link is clicked....
Here it is:
onclick=$('#finish_counting').click();
Now, this code might trigger another click event handler which is not shown in your post and presumably looks like this code:
$('#finish_counting').on('click', function(){
//Do some handling
})
UPDATE:
Taking a further look on your code lead me to the conclusion that you're in an infinite loop - the anchor tag and the jQuery code refers to the same ID.

This is actually just calling the method .click(). It is actually triggering a click event. I'm not sure why they'd want to do that, especially in the onclick attribute...but that's what this code does.

Related

Use a link ONLY when javascript is disabled

I have a social networking site for my college community and its working fine. There is a feature to like a post by other users. Liking is triggered using javascript's onClick() function.
Recently due to security reasons, many of our members disabled javascript.
Is there any way to redirect a user to a particular page if javascript is disabled? Otherwise the script should work.
For a more discriptive detail, assume my current code is like:
Item
what i want is something like:
Like
**but href should be active only if onclick() function dont work. is that possible? **
my site is built with php codeigniter. any solutions?
Just return false on the function that is called in the onClick event.
So either make sure that likeFunction() returns false. Or, return false afterwards with onClick="likeFunction(); return false;".
In general, you should always put a link in the href and not rely exclusively on JS. An anchor tag should not be abused with the onclick event to create pseudo-buttons. You might consider using a button tag if no link has to be put in the href.
Also, the href should start with the protocol (http://www.example.com instead of www.example.com).
Side note: You might consider attaching the JS event by calling addEventListener instead of using the onClick attribute. There are different cons and pros using either methods. I suggest you to have a look at this answer: addEventListener vs onclick.
Edit: As WillardSolutions suggested, you can use preventDefault to ensure the link is not opened when the onClick event is called. For further details, I suggest you to have a look at this answer: event.preventDefault() vs. return false
Don't muddy up your HTML, simply enhance it with JavaScript (see: Progressive Enhancement). This can be easily achieved with a CSS class and a document selector.
Given the HTML:
Like
You can add a self executing JavaScript function just before the </body> tag:
<script>
(function() {
document.querySelectorAll('a.like').forEach(function(item) {
item.removeAttribute('href');
item.onclick = function() {
/* add the likeFunction functionality here */
};
});
})();
</script>
That's pretty basic; it loops through all <a> tags that have class="like", removes the href attribute and adds the functionality from your current likeFunction() to the click event (if you copy the code from the likeFunction() to where indicated).
Obviously if JavaScript is disabled, the DOM isn't updated and your original HTML remains in place.
Note: forEach() support may be sketchy in Microsoft browsers.
Why not just use preventDefault()
// if js is disabled, this doesn't execute at all,
// so the link will work by default and take the user to the url defined inside the `href` tag.
document.getElementById('myLink').addEventListener('click', function(e) {
e.preventDefault(); // This will tell the browser not to follow the link.
... Do Awesome stuff here all day long
});
DEMO

Jquery unobstrusive validation not working with submit event on jquery

I'm working in a project in MVC, but I've been having trouble with the jquery validation. I have this event handler for the submit on jquery because I plan to use ajax on it.
$("#form-cart").on("submit",function(e){
// codes
});
But here's the case, even when the input is invalid, it still goes inside the anonymous function. The form is located inside a modal. But I saw some piece of code somewhere and tried it which is this.
$("#MyModal").on("submit","#form-cart",function (e){
//codes
});
Amazingly it works, and it doesn't go inside the anonymous function when the input is invalid. But yeah, here's the problem. From my understanding the, if the second one worked, the first one should also have worked, but it didn't. Can someone tell me the reason why? It really bottles me.. Thanks.
I suggest you to use body click event :
Here is example :
$("body").on("submit","#form-cart",function (e){
//codes
});

how to fire a callback before redirect?

I want to write a global method for my site.
That when the page jumps to another, before the redirection acts, show a waiting mask on the page.
So I'm wondering if there is some way to get an event before the redirect?
The following code explains what I want to do, but doesn't work.
$(function() {
$(document).on('before_redirect', function() {
// show the waiting mask.
});
});
The answer can not be so neat, I just want the GLOBAL METHOD, once this piece of javascript included, no need to write anything other place.
Pray for good solution!
What you want is the beforeunload or unload event. JQuery also provides the unload shorthand method (deprecated after 1.8). Different browsers handle these events inconsistently, so you'll want to test each and make sure that your solution is acceptable in each. Generally, you'll lose control of the window once you've allowed the request to proceed so a mask may or may not work as intended.
the simplest way is place the same class name on redirecting elements like buttons ,anchor tag like so and write code based on class.
Html
<a class="navigation" href="/nextpage"></a>
or
<button class="navigation"></button> //for this you need to put url onClick function
js
$(function() {
$(document).on('click', '.navigation', function() {
// show the waiting mask.
});
});

jQuery late binding of Ajax elements doesn't work

I'm really stuck with a jQuery issue and I hope someone can help me out...
So I have a list of options on the left, and when you click on one, a form is generated via Ajax on the right. There's this element in the form:
<input type="text" class="value" value="something">
And what I want to do is to call
$(".value").tagsInput();
which is a jQuery plugin that works pretty much like Stack Overflow's 'Tags' input field when you ask a question.
So I tried this:
$(document).ready(function() {
$(".value").on("load", function () {
console.log("Tags Input");
$(".value").tagsInput();
});
});
and nothing is printed out. I've also tried this:
$(document).on("change", ".value", function () {
console.log("Tags Input");
$(".value").tagsInput();
});
and it doesn't work either. I'm wondering where I did wrong. Can anyone help me out?
As pointed out by Shabnam, the "change" event is not what you want, as it is fired only once the field is blurred.
Anyways, from the plugin documentation, it looks like you don't have to call that function every time a key is pressed, but it attaches its own event handlers autonomously.
So, probably you should be fine with just:
$(document).ready(function() {
$(".value").tagsInput();
});
Your .on handler will never work, as the load event is fired only by document when the page is ready.
If you want to debug things a bit, have a look at the supported callbacks, such as onChange.
SIDE NOTE
I don't like how that plugin is written, as it clogs the "global" jQuery.fn namespace with lots of functions, while jQuery documentation recommends not doing so (see: Namespacing).
UPDATE
See here: http://jsfiddle.net/aFPHL/ an example of this working (the .load() was monkeypatched to avoid having to call an actual URL, but its behavior is pretty much the same as the real one).
"change" event gets fired when the input element loses focus. If you want ajax call at the end of each key input, try using keyboard events

Sending click event to parent anchor

How do I send a click event (JS or JQuery) to a parent object that is an anchor? My basic HTML looks like:
<a href="javascript:myFunc(1,2,3)">
<img id="btn1" src="myimg.png">
</a>
So I can easily reference the anchor through button via:
document.getElementById('btn1').parentNode
However,
document.getElementById('btn1').parentNode.click
while it doesn't seem to raise an error in the console on firebug, the javascript function doesn't seem to be firing either. How do I send a click to this thing. By the way, I don't have control of the HTML so I can't just ad an ID to the anchor tag.
Gone are the days when it's okay to use the href="javascript:blah", especially if you're using a library like jQuery, Dojo, ExtJs or the rest. Event handlers should always be attached outside of the HTML.
$(function() {
$("#btn1").click(function() {
$(this).parent().click();
};
});
Here is a snippet that you can test on SO pages (copy+paste into Firebug)
$("#hlogo a").click(function() {
alert("a!");
return false;
});
$("#hlogo a img").click(function() {
alert("img!");
$(this).parent().click();
});
Normal Links with Normal HREF's
// assuming the link is always the immediate parent of #btn1
$("#btn1").parent().trigger("click");
Links with Javascript-Commands as HREF's
I note in your case though that your HREF value is a call to a javascript function, with parameters. For this, you may want to evaluate that HREF, rather than click the link:
// run the href-javascript from the parent anchor
eval($("#btn1").parent().attr("href"));
I've built a test-case and used firebug to try both methods. The first returns 1, showing the link was clicked, but the javascript is never executed. The second method actually executes the javascript found within the HREF value of the link itself. This should be an adequate solution to your specific need.
EDIT: ignore this answer as it's no good for links; see the comments below.
The click property of an a element is a function property, aka a method; all you are doing is referencing the property, not invoking it.
document.getElementById('btn1').parentNode.click();
(note the () to cause the method to be invoked) should do it, though if you are using jQuery already then Jonathan Sampson's answer will do what you need - there's no point in loading the library and then not using it :-)
Although Jonathan's answer can be shortened, as jQuery provides a click method:
$("#btn1").parent().click();
jQuery way maybe like this:
$(event.target).closest('a').trigger('click')
or in your words something like this
$('#bth1').closest('a').trigger('click')

Categories