Calling click functions inside a main function - javascript

I just wanted to know about any downsides to calling click functions inside a main function rather than in the $(document).ready(function() {});. This is what i mean
function tester() {
$('.className-1').click(function() {
var cmtpid = $(this).attr('data-cmtpid');
alert(cmtpid);
});
$('.className-2').click(function() {
var pid = $(this).attr('data-pid');
alert(pid);
});
}
tester();
UPDATE : the tester() function will only be called once, this is all mainly because I want to avoid inline html onclick=""

Since I noticed you're using jQuery. Perhaps consider adding unbind("click") after the selector to ensure you don't accidentally bind the click more than once causing multiple executions upon click.
Also there isn't any REAL downside but I would HIGHLY recommended putting that java-script at the very end of your html document to ensure the DOM is loaded.
Example:
$('.className-1').unbind("click").click(function(){
});

Related

Trigger a button click on a moon.Button or moon.IconButton with jQuery/Javascript directly

I know the click action can be triggered by assigning ontap a specific function like so:
{
kind: "moon.Button",name :"search_button",
content : "Search" , ontap : "searchAction", classes: "menu-button-style"
}
.
.
.
searchAction : function(){ //do some stuff on click}
I've tried
$('#id_of_my_button').click();
$('#id_of_my_button').trigger('click');
and none of those seem to work.
simplified jsFiddle
Any ideas
Why trigger the click with jquery? You can force an event with Enyo, as well:
this.$.someButton.bubble("ontap", {...});
Here, try this:
http://jsfiddle.net/Djspaceg/2AWb5/6/
Enyo has a global handle (enyo) you can use if you need to access any part of its structure. It's not recommended for use from within our app, since it breaks encapsulation, but since you're already outside enyo (by using jQuery or plain JavaScript) I don't see as much harm.
function TapThat() {
// 'enyo' is the global namespace.
// The '$' refers to the children of the object/kind.
enyo.$.tappyButton.tapAction();
}
Using the native click function of elements seems to work in your case, like this:
window.onload = function (){
document.getElementById('tappyButton').click();
};
Demo
Your problem in the fiddle is that you haven't included jQuery. Also, probably that you don't wait for the element to be added to the DOM before binding a click listener to it.
Demo with jQuery

Javascript two clicks - need one

I'm total beginner in JavaScript. The problem is that the code works only when I click on the text two times. I need same, but with one click. The code is on the link:
http://jsbin.com/uTizoKe/1/edit?html,output
I'd really appreciate any help. Thank in advance
Move your script tag to the end of the body of the HTML, and remove the onclick handler from the table tag. This works (here's the jsbin):
<script>
document.getElementsByTagName('table')[0].onclick = setTDOnclickEvents();
function setTDOnclickEvents() {
var allTDs = document.getElementsByTagName("TD");
for (var i in allTDs) {
allTDs[i].onclick = function () {
txtCellData.value = this.innerHTML;
}
}
}
</script>
Another option (rather than calling your function based on a table click) is to simply do this:
<script>
var allTDs = document.getElementsByTagName("TD");
for (var i in allTDs) {
allTDs[i].onclick = function () {
txtCellData.value = this.innerHTML;
}
}
</script>
Another option is (if you want to use the script in the head of the document), put everything as a function inside of window.onload.
Additionally, it generally a good practice to try to avoid relying on putting event handlers inside HTML elements themselves, and rather handle all that stuff inside your JavaScript.
Remove the onclick from the table and add it as onload to the body
DEMO
Alternatively, you can use window.onload instead of putting it directly in the body
DEMO
The problem is that you have an onclick attached to the table which calls setTDOnclickEvents. So, only when the user clicks the table will that onclick occur.
What you really want is to bind your elements within the table when the page loads. Using jQuery you could do...
$(function() {
setTDOnclickEvents();
});
Replace
<body>
by
<body onload="setTDOnclickEvents()">
There are other ways to do that, like you could just write :
document.onload = setTDOnclickEvents;
Inside your JavaScript
You need to bind your function to an event for it to be fired at all, if it's inside head.
I'd expect your code not to work at all, strange that it does. Perhaps some default behavior somewhere, not worth investigating...
PS: I just saw that you're biding the click event for table to the function, so that would explain the strange behavior. Yeah, remove that.
The problem is that you're calling setTDOnclickEvents() on click of the table element. So you're not attaching the click events until after you've clicked the first time.
Instead, you can move this into the body onload attribute.
There are some other improvements you could make to this code to, to make it simpler and more up-to-date. If interested, please let me know, I'd be happy to help.

Check if the jQuery page load events fired already

Is there a way to check if jQuery fired the page load events yet, or do you have to roll your own? I need to alter the behavior of links, but I don't want to wait until the page finishes loading because the user could conceivably click on a link on, say, the top half of the page before the page finishes loading. Right now I'm doing it like this:
var pageLoaded = false;
$(function() {
pageLoaded = true;
});
function changeLinks() {
$("a[data-set-already!='true']").each(function() {
$(this).attr("data-set-already", "true").click(...);
});
// Is there something along the lines of jQuery.pageWasLoaded that I can
// use instead?
if (!pageLoaded) {
window.setTimeout(changeLinks, 100);
}
}
changeLinks(); // Added per #jondavidjohn's question
Since you are using the document ready shorthand, I'm guessing you mean when the dom is loaded. For this:
$.isReady
You could use setInterval and clear the interval on domready:
var changeLinksInterval = setInterval(function () {
$("a[data-set-already!='true']").each(function() {
$(this).attr("data-set-already", "true").click(...);
});
}, 100);
$(function () {
clearInterval(changeLinksInterval);
});
By the way, in your code example, you shouldn't need .each() - you should be able to call .attr() and .click() directly and let jQuery do the looping. Unless there is more to your .each() code that you didn't post.
$("a[data-set-already!='true']").attr("data-set-already", "true").click(...);
you could use .live() to initiate a click event that needs additional work when binding.
$("a[data-set-already!='true']").live(function(){
// since this event will only fire once per anchor tag, you
// can safely bind click events within it without worrying
// about getting duplicate bound click events.
var $this = $(this);
$this
.data("dataSetAlready",true)
.click(myClickHandler);
});
this is also a useful technique for late-initializing plugins on elements that may not exist at domReady.

Workaround for passing parameter to jQuery ready()

I have some code called on jQuery document.ready() which is used in multiple HTML files. Now the difference is each of these HTMLs uses a different div id.
I know one option is to just check for hardcode div ids inside $(document).ready() . But I wanted to write a generic code which would take the div Ids based on the currrent/calling HTML page?
So is there any way or workaround for passing parameter to jQuery ready() ?
$(document).ready() just wants a function as an argument so you can write a function that takes your ID as an argument and returns a function for $(document).ready(). For example, instead of this:
$(document).ready(function() {
$('#some_id').click(/*...*/);
});
you could do this:
function make_ready(id) {
return function() {
$('#' + id).click(/*...*/);
};
}
$(document).ready(make_ready('some_id'));
Then you could put your make_ready in some common location and use it to build the functions for your $(document).ready() calls.
document ready just takes in an handler function as a parameter.
You can still define a generic code in you document ready function, by storing the current div id for each html.
<input type="hidden" id="current_div" value="div1" />
$(document).ready(function() {
var div_id = $('#current_div').val();
// generic code
});

Passing argument to JS function from link onclick

I have a link that looks like this:
<a id="mylink" onclick="deleteHike( 3 );" href="javascript:void(0);">Yes</a>
It is able to call this JavaScript:
window.onload = function()
{
//Get a reference to the link on the page
// with an id of "mylink"
var a = document.getElementById("mylink");
//Set code to run when the link is clicked
// by assigning a function to "onclick"
a.onclick = function( hike_id )
{
// Somecode her
// But when I try to use the hike_id it displays as [object MouseEvent]
}
}
But the value that comes in is [object MouseEvent], not the number that I was expecting. Any idea why this happens and how to fix this? :)
Thanks!
You are trying to assign the function to your link in two different and conflicting ways.
Using the eval-ed function string, onclick = "function(value)", works but is deprecated.
The other way of binding the click handler in the onload event works too, but if you want a particular value to be passed, you'll have to change your script a bit because the value as given in the initial onclick is completely lost when you set the onclick to a new function.
To make your current method work, you don't need an onload handler at all. You just need this:
function deleteHike(hike_id) {
// Some code here
}
To do it the second way, which I recommend, it would look like this:
<a id="mylink" href="javascript:void(0);">Yes</a>
with this script:
function deleteHike(e, hike_id) {
// Some code here
// e refers to the event object which you can do nifty things with like
// - learn the actual clicked element if it was a parent or child of the `this` element
// - stop the event from bubbling up to parent items
// - stop the event from being captured by child items
// (I may have these last two switched)
}
function getCall(fn, param) {
return function(e) {
e = e || window.event;
e.preventDefault(); // this might let you use real URLs instead of void(0)
fn(e, param);
};
}
window.onload = function() {
var a = document.getElementById("mylink");
a.onclick = getCall(deleteHike, 3);
};
The parameter of a DOM event function is the event object (in Firefox and other standards-compliant browsers). It is nothing in IE (thus the need to also grab window.event). I added a little helper function for you that creates a closure around your parameter value. You could do that each time yourself but it would be a pain. The important part is that getCall is a function that returns a function, and it is this returned function that gets called when you click on the element.
Finally, I recommend strongly that instead of all this, you use a library such as jQuery because it solves all sorts of problems for you and you don't have to know crazy JavaScript that takes much expertise to get just right, problems such as:
Having multiple handlers for a single event
Running JavaScript as soon as possible before the onload event fires with the simulated event ready. For example, maybe an image is still downloading but you want to put the focus on a control before the user tries to use the page, you can't do that with onload and it is a really hard problem to solve cross-browser.
Dealing with how the event object is being passed
Figuring out all the different ways that browsers handle things like event propagation and getting the clicked item and so on.
Note: in your click handler you can just use the this event which will have the clicked element in it. This could be really powerful for you, because instead of having to encode which item it was in the JavaScript for each element's onclick event, you can simply bind the same handler to all your items and get its value from the element. This is better because it lets you encode the information about the element only in the element, rather than in the element and the JavaScript.
You should just be able to declare the function like this (no need to assign on window.onload):
function deleteHike(hike_id)
{
// Somecode her
// But when I try to use the hike_id it displays as [object MouseEvent]
}
The first parameter in javascript event is the event itself. If you need a reference back to the "a" tag you could use the this variable because the scope is now the "a" tag.
Here's my new favorite way to solve this problem. I like this approach for its clarity and brevity.
Use this HTML:
<a onclick="deleteHike(event);" hike_id=1>Yes 1</a><br/>
<a onclick="deleteHike(event);" hike_id=2>Yes 2</a><br/>
<a onclick="deleteHike(event);" hike_id=3>Yes 3</a><br/>
With this JavaScript:
function deleteHike(event) {
var element = event.target;
var hike_id = element.getAttribute("hike_id");
// do what you will with hike_id
if (confirm("Delete hike " + hike_id + "?")) {
// do the delete
console.log("item " + hike_id + " deleted");
} else {
// don't do the delete
console.log("user canceled");
}
return;
}
This code works because event is defined in the JavaScript environment when the onclick handler is called.
For a more complete discussion (including why you might want to use "data-hike_id" instead of "hike_id" as the element attribute), see: How to store arbitrary data for some HTML tags.
These are alternate forms of the HTML which have the same effect:
<a onclick="deleteHike(event);" hike_id=4 href="javascript:void(0);">Yes 4</a><br/>
<button onclick="deleteHike(event);" hike_id=5>Yes 5</button><br/>
<span onclick="deleteHike(event);" hike_id=6>Yes 6</span><br/>
When you assign a function to an event on a DOM element like this, the browser will automatically pass the event object (in this case MouseEvent as it's an onclick event) as the first argument.
Try it like this,
a.onclick = function(e, hike_id) { }

Categories

Resources