jQuery - Trigger a function - javascript

I am trying to trigger a function from a html file that is located in another function in js file. I am trying to use the trigger method but i cannot make it to work.
Any suggestions how to do this? FIDDLE
<div id="result4" style="color:white; background:black">
from function
</div>
<script>
var TEST = new test({
type: "image",
file: "test.jpg",
breakingPoint: 100
});
TEST.trigger('reset');
</script>
JS
function test(args) {
$this.on('reset', function() {
$("#result4").html("new text");
console.log("OK");
});
}

Looking at the console log, your fiddle has an error:
$this.on('reset', function() {
$("#result4").html("new text");
console.log("OK");
});
$this is not defined.
and looking at the documentation for trigger:
http://api.jquery.com/trigger/
you are invoking it wrong. You are creating your own object that does not have a trigger method.

You need to define $this and return it as the object for test since trigger is a jquery function and not a native JavaScript Object function.
function test(args) {
var $this = $(this); // declare $this
var default_options = {
breakingPoint: 2000
};
var options = $.extend({}, default_options, args);
$("#result1").html(options.type);
$("#result2").html(options.file);
$("#result3").html(options.breakingPoint);
$this.on('reset', function() {
$("#result4").html("new text");
console.log("OK");
});
return $this;
}
var TEST = new test({
type: "image",
file: "test.jpg",
breakingPoint: 100
});
TEST.trigger('reset');

Wrap you tag code in jquerys ready event. This will execute it once the DOM is loaded instead of as it is parsed.
Maybe this is what you're looking for:
<script>
$(document).ready(function(){
var TEST = test({
type: "image",
file: "test.jpg",
breakingPoint: 100
});
TEST.reset();
});
</script>
In JS File
var test = function(options){
var that = {};
// you can use type, file & breaking point with option.type options.file etc..
that.reset = function() {
$("#result4").html("new text");
console.log("OK");
};
return that;
};

Related

Triggering fluffy.js

I'm trying to make a simple tumblr theme using the fluffy plugin (https://github.com/mzdr/fluffy.js) but I've ran into a problem. The plugin only executes once on page load. I'm trying to get it to work with the infinite scroll plugin (http://www.infinite-scroll.com/) and I need the fluffy plugin to trigger whenever new content loads.
I'm fairly new when it comes to JS so I appreciate any help I can get. Thanks.
Edit added code:
<script src="https://code.jquery.com/jquery-2.2.2.min.js"></script>
<script src="https://npmcdn.com/imagesloaded#4.1/imagesloaded.pkgd.min.js"></script>
<script src="http://static.tumblr.com/hpghjri/co2nfnr1j/infinitescroll.min.js"></script>
<script src="http://static.tumblr.com/nxwjyyg/XWUob8gtq/fluffy.min.js"></script>
<script>
$(function(){
app.initInfinite();
app.onImagesLoad();
}); //end document ready
var app = {
'initInfinite' : function() {
var $container = $('.page-index .posts');
$container.infinitescroll({
navSelector:".pagination",
nextSelector:".pagination-next",
itemSelector:".posts__container",
appendCallback:true,
loading:{
finishedMsg:" ",
img:"data:image/gif;base64,R0lGODlhAQABAHAAACH5BAUAAAAALAAAAAABAAEAAAICRAEAOw==",
msg:null,
msgText:" ",
selector:null,
finished:function() {
}
}
},
function(newElements) {
var $newElems = $(newElements).css({opacity:0});
var $newElemsIDs = $newElems.map(function() {
return this.id;
Tumblr.LikeButton.get_status_by_post_ids($newElemsIDs);
}).get();
$newElems.imagesLoaded(function() {
$newElems.animate({opacity: 1});
//what to do when new elems appended
// I need to trigger fluffy here
});
var $newElemsIDs = $newElems.map(function() {
return this.id;
}).get();
Tumblr.LikeButton.get_status_by_post_ids($newElemsIDs);
});
},
'onImagesLoad' : function() {
$('.content .posts').imagesLoaded()
.always( function( instance ) {
console.log('all images loaded');
$('.overlay').addClass('hide');
$('.overlay__preloader').attr('class', '');
})
.done( function( instance ) {
console.log('all images successfully loaded');
});
}
}
</script>
This is your lucky day! I just released v2.1.0 which fixes your problem. Now you can create Fluffy objects on the fly like that:
// Start automatic detection
Fluffy.detect();
// Or provide a DOM node for single creation
var myElement = document.querySelector('#what-ever-you-like');
Fluffy.create(myElement);
// Or use a selector to create one
Fluffy.create('[data-fluffy-container]');
Don't forget to check out the updated docs.

Parameter in a jquery event

I want to pass an object called hotTraitement in parameters of an event .click of jquery. So I declare my object like this :
$(window).load(function(){
container = document.getElementById('tab_traitement');
var hotTraitement = new Handsontable(container, {
data: data_traitement});
});
And I'm trying to pass this object like this :
$('#submit_button_traitement').click(function({hotTraitement:hotTraitement})
{
console.log(hotTraitement);
});
But it's not working, hotTraitement is undefined.
Help please !
Try this.
Define the hotTraitement variable as global one.
$('#submit_button_traitement').click({hotTraitement:hotTraitement},function(e){
console.log(e.data.hotTraitement);
});
SIMPLE DEMO: FIDDLE
Update:
Try this way.
$(document).ready(function() {
var container = document.getElementById('tab_traitement');
var hotTraitement = new Handsontable(container, {
data: data_traitement
});
//...
$('#submit_button_traitement').click({
hotTraitement: hotTraitement
}, function(e) {
console.log(e.data.hotTraitement);
});
});
why you want to pass hotTraitement parameter in onclick function instead you can simply access this inside your onclick even like this
$(window).load(function(){
container = document.getElementById('tab_traitement');
var hotTraitement = new Handsontable(container, {
data: data_traitement});
$('#submit_button_traitement').click(function(){
console.log(hotTraitement);
});
});
Try substituting $(document).ready() for $(window).load() ; utilizing .on() , data property of event
$(document).ready([
function() {
// define `hotTraitement`
hotTraitement = {
"abc": 123
};
},
function() {
// set `event.data` to `hotTraitement`
$("#submit_button_traitement")
.on("click", hotTraitement, function(event) {
// do stuff with `event.data` : `hotTraitement`
console.log(event.data)
})
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="submit_button_traitement">click</div>

Create Jquery Plugin with dynamic parameters for MULTIPLE usage

I creating jquery plugin, looks like this :
(function ( $ ) {
// -- This is Person Object used for plugin
var PersonObject = function(elem, options)
{
this.elem = elem;
this.options = options;
this.run();
};
PersonObject.prototype = {
run: function()
{
// console.log(this.options.person_name);
self = this;
tpl = '<a class="btn btn-link btncok">one</a>';
self.elem.after(tpl);
$('.content').on('click', '.btncok', function(e) {
e.stopImmediatePropagation();
self.show();
});
return self.options.person_name;
},
show: function()
{
console.log(this.options.person_name);
}
};
// -- end Person Object
// -- This is my jquery fn function
$.fn.myPlugin = function(options) {
// here is default options
var default_options = {person_name: 'father'};
options = $.extend({}, default_options, options);
return this.each(function() {
new PersonObject($(this), options);
});
};
// -- end jquery plugin
}( jQuery ));
.
.
so then, when the above plugin are used by many elements with different situation like this :
<div class="jumbotron content">
<p class="something-one">one</p>
<p class="something-two">two</p>
</div>
<script>
// call the plugin WITH parameters
$('.something-one').myPlugin({person_name: 'mother'});
// result wrong : father (should be mother)
// call the plugin WITHOUT parameters
$('.something-two').myPlugin();
// result correct : father
</script>
the parameters is not work expected.
all the element that using the plugin will receive same parameters by last element call
how to fix this problem :(
You are seeing the same value because of the below click handler
$('.content').on('click', '.btncok', function(e) {
e.stopImmediatePropagation();
self.show();
});
$('.content').on('click', '.btncok', .... is does not delegate event as expected. Instead attach an event to tpl directly. Something like this
this.appendedEl = $('<a class="btn btn-link btncok">'+this.options.person_name+'</a>');
this.elem.after(this.appendedEl);
this.appendedEl.on('click', function(e) { // <--- this way the event is attached to the right element
e.stopImmediatePropagation();
this.show();
}.bind(this)); // <--- I used bind instead of self
Here is a demo http://jsbin.com/jafulo/edit?js,output

Very simple jquery custom function throws error

I have the following code:
$(document).ready(function() {
$.fn.addRemoveButton = function() {
alert(1);
};
$.addRemoveButton();
});
And I get the following error message from firebug:
TypeError: $.addRemoveButton is not a function
$.addRemoveButton();
Why and how can I fix this?
You need to define a selector, try this:
$(document).ready(function() {
$.fn.addRemoveButton = function() {
alert(1);
};
$(document).addRemoveButton();
});
Here is working jsFiddle.
You need to apply that to any DOM.
Example
jQuery Code
$(function()
{
$.fn.addRemoveButton = function() {
alert(1);
};
$('#letit').addRemoveButton();
});
HTML Code
<div id="letit"></div>
or, you can create it as a jQuery global function:
$(document).ready(function() {
$.addRemoveButton = function() { // removed the .fn
alert(1);
};
$.addRemoveButton();
});
This binds the function to the jQuery object, where you can then use it like in your original example.
See this post for the difference between jQuery.fn.method and jQuery.method

Events in Backbone.js

Can u help with the click event?? here is my code.
$(function() {
var Trainee = Backbone.Model.extend();
var TraineeColl = Backbone.Collection.extend({
model: Trainee,
url: 'name.json'
});
var TraineeView = Backbone.View.extend({
el: "#area",
template: _.template($('#areaTemplate').html()),
render: function() {
this.model.each(function(trainee){
var areaTemplate = this.template(trainee.toJSON());
$(this.el).append(areaTemplate);
},this);
return this;
}
});
var trainee = new TraineeColl();
var traineeView = new TraineeView({model: trainee});
trainee.fetch();
trainee.bind('reset', function () {
traineeView.render();
});
});
my o/p after(trainee.toJSON) is
Sinduja
E808514
HPS
Shalini
E808130
HBS
Priya
E808515
HSG
Everything is fine with the o/p...
Now i want to get this o/p oly after a button click....
Simply add an event to that button. Since you're using jQuery, that should be simple :
$(function () {
$("#your_button_id").on("click", function (e) {
e.preventDefault();
// your code here
});
});
I don't understand what the o/p is...
Anyway, you can do something like that :
trainee.bind('reset', function () {
$('button').click(function() {
traineeView.render();
});
});
with the proper jQuery selector $('button') for your button...

Categories