How to initialize a plugin from another javascript file - javascript

I have the following fiddle. On click of button 'scroll', is it possible to call the scrollTest function inside the plugin? Right now I am calling the whole test() again and hence it is creating a new test object each time I click on scroll button.
My Code [ fiddle demo ]
(function ($, win, doc) {
'use strict';
$.fn.test = Plugin;
$.fn.test.Constructor = Test;
function Plugin() {
return this.each(function () {
new Test(this);
});
}
// TREE CLASS DEFINITION
// =====================
function Test(el) {
var publ = this,
priv = {};
console.log("start");
$('.test_button').click(function(){
console.log("clicked");
publ.scrollTest
})
publ.scrollTest = function () {
console.log("in scrolltest");
};
publ.bindEvents= function () {
console.log("in bind");
};
publ.fileter= function () {
console.log("in filter");
};
}
}(jQuery, this, this.document));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<h2>Hello</h2>
<button class="test_button">Click me</button>
<button class="test_button2" onclick="$('h2').test()">scroll</button>
</body>
<script>
$('h2').test();
</script>

You need to wrap the use of it inside a $(document).ready(); block to ensure the script has loaded before starting to use it.
If you wish to have your code only run onClick for elements with the class test_button2 you can use :
// include this only ONCE on your page.
$(document).ready(function() {
$(this).test(true); // sends the flag to initialize the click() event once
$('.test_button2').click(function(){
$(this).test(); // action on every .test_button2 click();
});
});
.. and replace ..
<button class="test_button2" onclick="$('h2').test()">scroll</button>
.. with ..
<button class="test_button2">scroll</button>
See the code below for the fix in action :
(function ($, win, doc) {
'use strict';
$.fn.test = Plugin;
var publ, priv;
function Plugin(initialize) {
if(initialize === true) {
console.log("start");
$('.test_button').click(function(){
console.log("clicked");
});
}
console.log("in scrolltest");
}
}(jQuery, this, this.document));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<h2>Hello</h2>
<button class="test_button">Click me</button>
<!-- onClick is handled by jQuery's .click() method -->
<button class="test_button2">scroll</button>
</body>
<script>
// this code should only be placed once on your page.
var $test;
$(document).ready(function() {
$test = $(this).test(true);
$('.test_button2').click(function(){
$(this).test();
});
});
</script>

Related

Inside an added jQuery function, can I know the triggered DOM object?

I added a simple function:
$.postAndVerify = function(url)
{
// this.event. ?
}
$('#myButton').click(function() {
$.postAndVerify('/url');
});
inside in it, how do I know the caller object, i.e. #myButton? Of course I know it could be just passed:
$.postAndVerify = function(url, $triggeredBy)
{
}
$('#myButton').click(function() {
$.postAndVerify('/url', $(this));
});
but it then would result tons of boilerplate code.
You could make it a plugin method by assigning the method to $.fn instead of to $
$.fn.postAndVerify = function(url){
console.log(this)// jQuery object
}
$('#myButton').click(function() {
$(this).postAndVerify('/url' );
});
Or you could use Function#bind()
You can try to use call method to pass button element as this
$.postAndVerify = function (url) {
console.log('this:');
console.log(this);
};
$('#myButton').click(function () {
$.postAndVerify.call(this, '/url');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="myButton" type="button">Click me</button>

how to run all functions in one click

I want help in solving this problem
I want to run all functions in one click how can I do this
Is the code of jquery
/*global $*/
$(function () {
'use strict';
$(".click1 button").on("click", function click1() {
$(this).parent(".click1").css("background-color", "#f00");
});
$(".click2 button").on("click", function click2() {
$(this).parent(".click2").css("background-color", "#ff0");
});
$(".click3 button").on("click", function click3() {
$(this).parent(".click3").css("background-color", "#f0f");
});
$("clickAll").on("click", function () {
click1();
click2();
click3();
});
});
You can use trigger function.
/*global $*/
$(function () {
'use strict';
$(".click1 button").on("click", function click1() {
$(this).parent(".click1").css("background-color", "#f00");
});
$(".click2 button").on("click", function click2() {
$(this).parent(".click2").css("background-color", "#ff0");
});
$(".click3 button").on("click", function click3() {
$(this).parent(".click3").css("background-color", "#f0f");
});
$("clickAll").on("click", function () {
$(".click1 button").trigger("click");
$(".click2 button").trigger("click");
$(".click3 button").trigger("click");
});
});
Use .triggerHandler to fire the event without bubbling:
/*global $*/
$(function() {
'use strict';
var clickMe = function(event, parent, bgColor) {
$(event.target).parent(parent).css("background-color", bgColor);
};
var $click1Button = $(".click1 button");
$click1Button.on("click", function(event) {
clickMe(event, ".click1", "#f00");
});
var $click2Button = $(".click2 button");
$click2Button.on("click", function(event) {
clickMe(event, ".click2", "#ff0");
});
var $click3Button = $(".click3 button");
$click3Button.on("click", function(event) {
clickMe(event, ".click3", "#f0f");
});
$(".clickAll").on("click", function() {
$click1Button.triggerHandler("click");
$click2Button.triggerHandler("click");
$click3Button.triggerHandler("click");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="click1"><button>click1</button></div>
<div class="click2"><button>click2</button></div>
<div class="click3"><button>click3</button></div>
<div class="clickAll"><button>clickAll</button></div>
Since the code executed in each handler is slightly the same, you can use event delegation to reduce the code required and moving what's related to the view in your html markup.
$(function(){
$("#common_ancestor").on('click', function (evt){
let $button = $(evt.target)
// Depending on your markup, you way use closest() or parents() instead of parent() here.
, $parent = $button.parent()
, clickSelector = '[class*="click"]'
;
// Test which button was triggered based on its parent
if ($parent.is('.clickAll')) {
$(this).find(clickSelector).each(function() {
this.style.backgroundColor = $(this).data('color');
})
} else if ($parent.is(clickSelector)) {
$parent[0].style.backgroundColor = $parent.data('color');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="common_ancestor">
<div class="click1" data-color="#f00"><button>click1</button></div>
<div class="click2" data-color="#ff0"><button>click2</button></div>
<div class="click3" data-color="#f0f"><button>click3</button></div>
<div class="clickAll"><button>clickAll</button></div>
</div>
Pros on using event delegation:
You don't need to register listener again when injecting additionnal <div class="clickn" data-color="#ff0"><button>clickn</button></div> elements in "#common_ancestor" div.
Only one function object is created in memory.
Cons:
- If you have non trivial behavior or code that differs slightly between targes, your uniq handler might quickly become bloated, which might affect code readability a lot in the long term.

how to call a jquery click function using javascript?

I wand to call a jquery click function using JavaScript
<input type='button' class="button" value='+Add' id='addImage'>
when i click this button the following function will run
$("#addImage").click(function () {
//my code.....
}
but i need to call this function using another JavaScript function like fn_name()
You can use trigger and the name of the event, like so (the example below uses a self-executing function for simplicity):
$("#addImage").click(function() {
alert('Clicked')
});
(function(){
$("#addImage").trigger('click')
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='button' class="button" value='+Add' id='addImage'>
use trigger
$("#addImage").trigger("click")
you have this ugly way too, but not recommended:
https://jsfiddle.net/96oxhwsf/
function fn_name() {
$("#addImage").click(function() {
alert('test')
});
}
fn_name()
beatiful way:
function fn_name(elID) {
let btn = document.getElementById(elID);
btn.addEventListener('click', function() {
alert('Test');
}, false)
}
// still need call the function
fn_name('addImage');
even better:
var addImg = () => {
let btnAdd = document.getElementById('addImage')
btnAdd.addEventListener('click', () => {
alert('test')
}, false)
}
declare function
bind click event
call function
//declare
function test(){
//my code.....
}
function callTest(){
// call function
test();
}
function callAClick(){
//trigger
$("#addImage").trigger('click')
}
// bind click
$("#addImage").click(test);

How do I execute a function once per page refreshing?

I have a code like this:
function myfunc () {
alert('executed');
}
$('.classname').on('click' function () {
myfunc();
});
I want to run myfunc once. I mean I don't want to execute it every time when user clicks on .classname element. I guess I need to warp function-calling into a condition. Something like this:
if ( /* that function never executed so far */ ) {
myfunc();
}
How can I do that?
The simplest way with jQuery is to use .one
function myfunc() {
alert('executed');
}
$('.classname').one('click', function() {
myfunc();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="classname">click here!</button>
You should remove the event listener in the function you're calling:
function myfunc () {
alert('executed');
$('.classname').off('click', myfunc);
}
$('.classname').on('click', myfunc);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='classname'>Click Me</div>
Don't set a global variable like the other posts describe - there's no need for that and then you're still doing an unnecessary function call. This ensures the function is never called again and the event isn't being listed for.
$( document ).ready(function() {
var hasBeenExecuted = false;
function myfunc () {
alert('executed');
hasBeenExecuted = true;
}
$('.classname').on('click' function () {
if(!hasBeenExecuted){
myfunc();
}
});
});
var functionWasRun = false;
function myfunc () {
functionWasRun = true;
alert('executed');
}
$(document).ready(function() {
$('.classname').on('click', function () {
if (!functionWasRun) {
myfunc();
}
});
});
I would suggest, as an alternative to a global variable, assigning a property to the function.
function myfunc () {
alert('executed');
myfunc.executed = true;
}
$('.classname').on('click', function () {
if(!myfunc.executed) {
myfunc();
}
});
This has the advantage of working the same way while not polluting the global scope unnecessarily. However, if skyline3000's answer works for you, you should use that instead as it's cleaner and more sensible overall.

Create click event in jquery plugin

I want to make simple plugin to show alert if class is binding by a jquery plugin.
below is my html code
<html>
<head>
<script src="js/modal-load.js"></script>
<script>
$(document).ready(function(){
$('.modal-link').modalLoad();
})
</script>
</head>
....
<body>
<div class="hblock-1 text-4 text__uppercase color-7">
<a class="login btn btn-primary modal-link" href="/login-modal.php" data-toggle="modal" data-target="#login-modal">Log in</a>
Register
</div>
</body>
This is my plugin script
(function($){
$.modalLoad = function(element, options){
var defaults = {
foo: 'bar',
onFoo: function() {}
}
var plugin = this;
plugin.settings = {};
var $element = $(element),
element = element;
plugin.init = function(){
plugin.settings = $.extend({},defaults, options);
plugin.add_bindings();
}
plugin.add_bindings = function(){
this.click(function(){
alert('a');
})
}
plugin.create_modal = function(){
$('body').append('<div class="modal-wrapper"></div>');
}
plugin.init();
}
$.fn.modalLoad = function(options){
return this.each(function(){
if(undefined == $(this).data('modalLoad')){
var plugin = new $.modalLoad(this, options);
$(this).data('modalLoad', plugin);
}
});
}
})(jQuery);
In html code, i've initialized modalLoad plugin. But when particular class that i've bind, it won't be triggered by click event.
What's wrong with my code? is any mistake with my DOM selector in add_bindings part?
Thanks for advance
*edited
You need to attach the click handler to $element not this. Inside add_bindings, this refers to the plugin object not the clicked element so this will not have a method named on(You should get an error like Uncaught TypeError: undefined is not a function in your console)
plugin.add_bindings = function () {
$element.click(function (e) {
alert('a');
e.preventDefault()
})
}
Demo: Fiddle

Categories

Resources