I'm using jQuery for a while but it is the first time I need to create my own function. (I'm using noConflict)
I have a code who work like this :
jQuery(function()
{
jQuery("#tabs-3").dynatree({
checkbox: true,
onActivate: function(dtnode) {
alert("You activated " + dtnode);
}
});
//etendre tt les noeuds
jQuery("#tabs-3").dynatree("getRoot").visit(function(dtnode){
dtnode.expand(true);
});
});
The code above is working, BUT, this part of code is in an ajax call, it worked for the first time when I called it, but not the second time or in future. when i call it with a function it gives error "jQuery.mytree is not a function". So what's wrong in my code. please help me .
(function(jQuery){
jQuery.fn.extend({
mytree: function (mytreename)
{
alert(mytreename);
jQuery(mytreename).dynatree({
checkbox: true,
onActivate: function(dtnode) {
alert("You activated " + dtnode);
}
});
}
});
jQuery.mytree('#tabs-3');
})(jQuery);
Thanks!
That's because when you do jQuery.fn.extend, it extends your selector.
For example:
<div id = "tabs-3"></div>
<script type="text/javascript">
(function(jQuery){
jQuery.fn.extend({
mytree: function mytree() {
console.log("My tree ", this.attr("id"));
// Do your cool AJAX calls
}
});
jQuery("#tabs-3").mytree();
})(jQuery);
</script>
Will work. Inside mytree(), this is the result of your selector.
you have to call like,
jQuery("#tabs-3").mytree();
Arf I run into the next problem due to my construction I believe. The function is in a php lets call it 1.php.
1.php call in ajax 2.php
2.php contain a code who create a structure in ... (this part works).
In 2.php I call mytree, I don't get any error and the log works. But the dynatree doesn't work.
jQuery.fn.extend({
mytree: function mytree() {
console.log("My tree ", this.attr("id"));
jQuery(this.attr("id")).dynatree({
checkbox: true,
onActivate: function(dtnode) {
alert("You activated " + dtnode);
}
});
}
});
Anything to do for it to work?
Thanks!
To call dynatree,
jQuery.fn.extend({
mytree: function mytree() {
console.log("My tree ", this.attr("id"));
jQuery("#"+this.attr("id")).dynatree({
checkbox: true,
onActivate: function(dtnode) {
alert("You activated " + dtnode);
}
});
}
});
Aaaaaaaaaaaand I missed the "#" ;)
Ok, now It works like earlier, the first time I call the ajax everything is all right.
But when I click back on the link who call the ajax I get the ul li part not on dunatree. I have the log so it pass in the function. I can't figure why it doesn't make ul li in dynatreee. :(
Got the answer here!
I call now the function on the success call ajax on 1.php. (I think it's best coding just for that)
But before i check may tabs content, if it's not empty (previous tree) i destroy it before recreate it.
success : function(msg)
{
if(msg!="")
{
//jQuery("#tabs-3").html(msg);
(function(jQuery){
//alert('Pass!'+jQuery("#tabs-3").text());
if(jQuery("#tabs-3").text()!="")
{
jQuery("#tabs-3").dynatree("destroy");
}
jQuery("#tabs-3").html(msg);
jQuery("#tabs-3").mytree();
})(jQuery);
}
}
Maybe not the more efficient but the best i found ;)
Special thanks to arun kumar!
Related
As I was making a gallery for a webpage I ran into a problem with js automatically running the (next_image) function, after some searching around I found out it was due to the () after the statement.
however, I can not for the life of me figure out how else to get the clicked_id to the next_image function.
So my question is: how can I make it so that the function runs only after clicking the button while still sending the clicked_id?
function opencase(clicked_id) {
document.getElementById("right_arrow").addEventListener("click", next_image(clicked_id));
}
function next_image(photoid){
console.log(photoid);
photoid++;
document.getElementById("disp").setAttribute("src", "images/image"+photoid+".jpg");
console.log(photoid);
}
Any help will be greatly appreciated :D
Instead of directly calling the function , call it from the addEventListener callback function
function opencase(clicked_id) {
document.getElementById("right_arrow").addEventListener("click", function() {
next_image(clicked_id)
});
}
function next_image(photoid) {
console.log(photoid);
photoid++;
document.getElementById("disp").setAttribute("src", "images/image" + photoid + ".jpg");
console.log(photoid);
}
I am a beginner and having a problem with calling functions that I create on JavaScript or jQuery.
if i use this, it works:
$("#objectId").click(function(){
alert("Clicked on objectId")
}
however if I pre-define a function and call it onclick it doesn't work
function alertOnClick(objectToClick) {
alert("Clicked on " + objectToClick)
}
$("#objectId").click(alertOnClick("objectId"))
in this case, it gives the alert when the page is loaded and it does not alert on click.
What am I doing wrong syntax-wise and why?
Thank you very much
To achieve this, you need to return a function from alertOnClick as shown:
function alertOnClick(objectToClick) {
return function() {
alert("Clicked on " + objectToClick)
}
}
Which will allow you to do the following:
$("#objectId").click(alertOnClick("objectId"))
Here's a working code sample to see it in action:
function alertOnClick(objectToClick) {
return function() {
alert("Clicked on " + objectToClick)
}
}
$("#objectId").click(alertOnClick("objectId"))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js">
</script>
<button id="objectId">Object Id</button>
Because you are calling the function alertOnClick instead of passing it as reference
You should be doing something like this:
$("#objectId").click(alertOnClick)
function alertOnClick(ev) {
alert("Clicked on " + ev.target.id);
}
When you do $("#objectId").click(alertOnClick("objectId")) you are calling the alertOnClick method with objectId as parameter before the click event happens. What you should do is pass the reference of the method so it is called when the click event happens.
Good Day, this maybe a silly question :) how can I pass a parameter to an external javascript function using .on ?
view:
<script>
var attachedPo = 0;
$this.ready(function(){
$('.chckboxPo').on('ifChecked', addPoToBill(attachedPo));
$('.chckboxPo').on('ifUnchecked', removePoToBill(attachedPo ));
});
</script>
external script:
function addPoToBill(attachedPo){
attachedPo++;
}
function removePoToBill(attachedPo){
attachedPo--;
}
but Im getting an error! thanks for guiding :)
You need to wrap your handlers in anonymous functions:
$('.chckboxPo')
.on('ifChecked', function() {
addPoToBill(attachedPo);
})
.on('ifUnchecked', function() {
removePoToBill(attachedPo);
});
You can also chain the calls to on as they are being attached to the same element.
If your intention is to count how many boxes are checked, via passing variable indirectly to functions try using an object instead like this:
JSFiddle: http://jsfiddle.net/TrueBlueAussie/pBkhX/
var attachedPo = {
count: 0
};
$(function () {
$('.chckboxPo')
.on('change', function () {
if ($(this).is(':checked')) {
addPoToBill(attachedPo);
} else {
removePoToBill(attachedPo);
}
$("#output").prepend("" + attachedPo.count + "<br/>");
});
});
function addPoToBill(attachedPo) {
attachedPo.count++;
}
function removePoToBill(attachedPo) {
attachedPo.count--;
}
If it is not doing anything else you can simplify the whole thing to count checked checkboxes:
$(function () {
var attachedPo = 0;
$('.chckboxPo')
.on('change', function () {
attachedPo = $(".chckboxPo:checked").length;
});
});
"DOM Ready" events:
you also needed to wrap it in a ready handler like this instead of what you have now:
$(function(){
...
});
*Note: $(function(){YOUR CODE HERE}); is just a shortcut for $(document).ready(function(){YOUR CODE HERE});
You can also do the "safer version" (that ensures a locally scoped $) like this:
jQuery(function($){
...
});
This works because jQuery passes a reference to itself through as the first parameter when your "on load" anonymous function is called.
There are other variations to avoid conflicts with other libraries (not very common as most modern libs know to leave $ to jQuery nowadays). Just look up jQuery.noConflict to find out more.
I'm using selecter jquery. I initialize it by typing the code
$("select").selecter();
I need to make sure that the formstone selecter jquery library has completed before i start appending elements. So what i did is to is use the $.when function
initialize: function(){
$.when($("select").selecter()).then(this.initOptions());
},
initOptions: function(){
this.$el.find('.selecter').addClass('something');
}
But this does not work. How can i wait while formstone selecter is doing its thing before i execute another function?
Thanks,
UPDATE
Here's the update of what i did but it does not work.
initialize: function(){
$("select").selecter({callback: this.initOptions });
},
initOptions: function(){
this.$el.find('.selecter').addClass('something');
}
There is a callback option.
The function passed as a callback will receive the newly selected value as the first parameter
Should be $("select").selecter(callback: function() { alert('callback fired.') });
or as shown
$("select").selecter({
callback: selectCallback
});
function selectCallback(value, index) {
alert("VALUE: " + value + ", INDEX: " + index);
}
The problem which I think regarding the callback edited code is that this can refer to anything. Try the following code
var selectorObj = {
initialize: function(){
$("select").selecter({callback: selectorObj.initOptions });
},
initOptions: function(){
this.$el.find('.selecter').addClass('something');
}
};
Created a working fiddler for you http://jsfiddle.net/6Bj6j/
The css is out of shape. Just select what is poping up when you click on the dropdown. You will get an alert which is written in the callback.
The problem with the provided snippet is the scope of the callback:
var selectorObj = {
initialize: function(){
$("select").selecter({ callback: selectorObj.initOptions });
},
initOptions: function(){
// 'this' refers to the "$('.selecter')" jQuery element
this.addClass('something');
}
};
However if you just need to add a class to the rendered element, you should use the 'customClass' option:
$("select").selecter({
customClass: "something"
});
If you need to do more, you can always access the Selecter element directly:
var $selecter = $("select").selecter().next(".selecter");
$selecter.addClass("something").find(".selecter-selected").trigger("click");
Sidenote: I'm the main developer of Formstone. If you have any suggestions for new features or better implementation, just open a new issue on GitHub.
This should be quite simple but I'll be darned if I can work it out. Just trying to get a div to display while my ajax is processing and then hide once done (I've put a sleep in there purely to test its working as locally it loads so fast I'm not sure if its working or not)!
The html page has this code in the script: -
$(document).ready(function(){
$("#loadingGIF").ajaxStart(function () {
$(this).show();
});
$("#loadingGIF").ajaxStop(function () {
window.setTimeout(partB,5000)
$(this).hide();
});
function partB(){
//just because
}
var scenarioID = ${testScenarioInstance.id}
var myData = ${results as JSON}
populateFormData(myData, scenarioID);
});
There is then a div in my page like so (which I can see in the source of the page just hidden): -
<div id="loadingGIF" ><img src='${application.contextPath}/images/spinner.gif' height="50" width="50"></div>
The ready code then goes off and calls this: -
function populateFormData(results, scenarioID) {
$table = $('#formList')
for(var i in results){
var formIDX = (results[i]["forms_idx"])
var formID = (results[i]["form_id"])
appendSubTable(formIDX, scenarioID, $table, formID);
}
}
Which references this multiple times calling several AJAX posts: -
function appendSubTable(formIDX, scenarioID, $table, formID) {
var $subTable = $table.find("#" + formIDX).find('td:eq(1)').find("div").find("table")
var url = "**Trust me this bits OK ;) **"
$.post(url, {
formIDX : formIDX, scenarioID : scenarioID, formID :formID
}, function(data) {
$subTable.append(data)
}).fail(function() {
});
}
Any pointers gratefully received...
Interestingly I bunged some alerts into my ajaxstart and stop and neither show up ever so I'm missing something obvious :S When I check the console in firefox I can see that all my POSTs are completing....
You should probably add the Ajaxstart and stop global event handlers to the document node like this
$(document).ajaxStart(function () {
$("#loadingGIF").show();
});
I realized my problem, I needed to register the ajaxstart and stop to the document not the div!
So instead of this: -
$("#loadingGIF").ajaxStart(function () {
$(this).show();
});
I now have: -
$(document).ajaxStart(function () {
$("#loadingGIF").show();
});
I assume this is because its the document that the ajax is running against not the div although my understanding there may not be 100% accurate at least this works so please tell me if I've misunderstood this! :)
#jbl, thanks for this pointer I did this to also leave the notification on screen for a few more moments just to make sure everything is loaded.