Calling Javascript Functions by name - javascript

If I have an element on the page like this ...
<span data-function="DoSomething">Click</span>
... and i put this in my page header ...
$(document).ready(function()
{
$('[data-function]').each(function()
{
var fName = $(this).attr('data-function');
$(this).click(fName);
});
});
... what goes in place of the comment produce the desired effect of executing the function called "DoSomething".
Note:
I no the code above wont work, my question is how to make this work (translate 'DoSomething' in to DoSomething();)
Any ideas guys?

The functions should be available. Try putting them in an Object, like this:
$(document).ready(function()
{
var fns = {
DoSomething: function() {/* ... */},
DoAnotherthing: function() {/* ... */}
};
$('[data-function]').each(function()
{
var fName = $(this).attr('data-function');
$(this).click(fns[fName]);
});
});
Here's a jsfiddle, demonstrating a way to keep everything local to one namespace and assigning handlers based on the data attribute of elements.

Try calling function with window object -
$(document).ready(function() {
$('[data-function]').each(function() {
var fName = $(this).attr('data-function');
if (typeof (window[fName]) === "function") {
$(this).click(window[fName]);
}
});
}

You can use something like
$(this).click(window[fName]);
Where window would be replaced by the appropriate expression if the function DoSomething is not defined in the global scope.

Maybe a little bit clean way:
http://jsfiddle.net/whsPG/
var myfuncs = {
alert : function() {
alert("An Alert");
},
changeName: function(obj) {
$(obj).text('Other Text');
}
};
$('[data-function]').on('click', function()
{
value = $(this).data('function');
if (myfuncs.hasOwnProperty(value)) {
myfuncs[value](this);
}
});
​

Related

Event listener not firing on click

I am creating a simple function to close a flash message div on click event, but my listener is not firing.
I wrote 3 different functions to try to get it working, but nothing is happening and Chrome console isnt telling me anything.
My first was in ES6 class style, this one:
class closeFlashMessages {
constructor () {
this.getFlashMessages = document.querySelector("#flash-messages");
this.addEventListeners();
}
close () {
console.log(this.getFlashMessages);
this.getFlashMessages.className = "hide";
}
addEventListeners () {
if(this.getFlashMessages)
this.getFlashMessages.addEventListener("click", this.close);
}
}
new closeFlashMessages();
My second was this:
(function (){
let getFlashMessages = document.querySelector("#flash-messages");
function close () {
console.log(getFlashMessages);
getFlashMessages.className = "hide";
}
function addEventListeners () {
getFlashMessages.addEventListener("click", function () {
close()
});
}
addEventListeners();
});
My last one is this:
(function (){
let getFlashMessages = document.getElementById("flash-messages");
getFlashMessages.addEventListener("click", close(getFlashMessages));
function close (id) {
console.log(getFlashMessages);
getFlashMessages.className = "hide";
}
});
My HTML:
<div id="flash-messages">
<div class="flash success">
<p>Recept byl přidán do nákupního seznamu.</p>
</div>
</div>
But none of them worked!! I dont understand
With the first two, I was getting undefined on my this.getFlashMessages also not sure why.
My solution is not in ES6
function Init(){
var id = document.getElementById('flash-messages');
var msg = document.querySelector('.flash');
id.addEventListener('click',function(){
msg.className = 'hide';
});
}
Init();
see demo here
I am not very much familiar with ES6.
But if I try similar code sample on a javascript it will be as given below and I hope it will be almost similar in ES6 aswell.
var getFlashMessages = document.getElementById("flash-messages");
getFlashMessages.addEventListener("click", function()
{
clicked(getFlashMessages);
});
function clicked(id){
console.log(id);
id.className = "hide";
}
Here, I am calling anonymous function, and its default argument will be event object as given in https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener.

if statement within function breaks javascript

I'm stumped with this one and would really appreciate someone's help.
I'm customizing highslide for integration with wordpress. Via the following code within the highslide.config.js file I'm adding a class name to certain elements and passing different attributes through an onClick call depending on certain conditions.
Everything works until I add the following code:
if(hsGroupByWpGallery){
slideshowGroup: this.parentNode.parentNode.parentNode.id
};
When the above code is present, not only does that one statement not execute, but the whole thing stops working. Even if the if statement is something like if(1=1){}; it still breaks.
If I have instead simply slideshowGroup: this.parentNode.parentNode.parentNode.id or nothing (the two options I'm looking for), both do what I would expect. I just need an if statement to switch between them.
Here's the relevant code:
jQuery(document).ready(function() {
var hsCustomGalleryGroupClass = 'fbbHighslide_GalleryGroup';
var hsCustomGalleryGroupChecker = 0;
var hsGroupByWpGallery = true;
jQuery('.' + hsCustomGalleryGroupClass).each(function(){
hsCustomGalleryGroupChecker++;
return false;
});
if (hsCustomGalleryGroupChecker > 0){
jQuery('.' + hsCustomGalleryGroupClass).each(function(i, $item) {
var grpID = $item.id;
jQuery('#' + grpID + ' .gallery-item a').addClass('highslide').each(function() {
this.onclick = function() {
return hs.expand(this, {
slideshowGroup: grpID
});
};
});
});
} else {
jQuery('.gallery-item a').addClass('highslide').each(function() {
this.onclick = function() {
return hs.expand(this, {
// This is the problem if statement
if(hsGroupByWpGallery){
slideshowGroup: this.parentNode.parentNode.parentNode.id
};
});
};
});
};
});
Thanks in advance.
The problem is you are trying to assign a conditional property.. you can't have a if condition inside a object definition like that
jQuery('.gallery-item a').addClass('highslide').each(function () {
this.onclick = function () {
var obj = {};
//assign the property only if the condition is tru
if (hsGroupByWpGallery) {
obj.slideshowGroup = this.parentNode.parentNode.parentNode.id;
}
return hs.expand(this, obj);
};
});
Another way to do the same is
jQuery('.gallery-item a').addClass('highslide').each(function () {
this.onclick = function () {
//if the flag is true sent an object with the property else an empty object
return hs.expand(this, hsGroupByWpGallery ? {
slideshowGroup: this.parentNode.parentNode.parentNode.id
} : {});
};
});
I think you might want this, based on the other code:
jQuery('.gallery-item a').addClass('highslide').each(function() {
this.onclick = function() {
if(hsGroupByWpGallery){
return hs.expand(this, {
slideshowGroup: this.parentNode.parentNode.parentNode.id
});
}
};
});

Javascript - On('Click') - Error - Calling On Page Load

<script>
function playController(dataObj){
alert(dataObj);
}
function playHandlers(){
var dataObj = "stef";
$('.audiocontrol').on('click', playController(dataObj));
}
$(document).ready(playHandlers);
</script>
This bit of code is firing off on page load whether I click the object or not. Why?
What you want is:
function playController(dataObj){
alert(dataObj);
}
function playHandlers(){
var dataObj = "stef";
$('.audiocontrol').on('click', function() { playController(dataObj); } );
}
$(document).ready(playHandlers);
The way your code was written, it was calling playController when you were registering it in the .on call.
jsfiddle
You're invoking the function therefore passing the result of playController. You can do something like this.
function playHandlers(){
var dataObj = "stef";
$('.audiocontrol').on('click', function() {
playController(dataObj);
});
}
This will work:
(demo here)
function playController(dataObj) {
alert(dataObj);
}
function playHandlers() {
var dataObj = "stef";
$('.audiocontrol').on('click', function () {
playController(dataObj)
});
}
$(document).ready(playHandlers);
This will load your code when the page loaded and call the function playHandlers(). You were calling it directly because you forgot to add function(){} in the on/click call.

Undefined property of variable in jquery

What is the proper way to make this code work?
$(function(){
var base = {
$wrapper: $('.homepage_main'),
$main: base.$wrapper.find('#primary').find('.home_slides').closest('[data-id="Colleague"]'),
$panel: base.$wrapper.find('#sidebar').find('.home_slides').closest('[data-id="Colleague"]'),
Template: {
$img: function () { return $('img'); }
},
Modal: {
$modalInterrupt: $('#searching_interruption'),
Suggestion: {
$self: $('#suggested_colleague'),
$loading: base.Modal.Suggestion.$self.find('.gif_loading'),
$paging: base.Modal.Suggestion.$self.find('.pagination'),
$itemContainer: base.Modal.Suggestion.$self.find('.request_items'),
$itemClone: base.Modal.Suggestion.$itemContainer.find('[data-id="Clonable"]').clone().removeAttr('data-id').removeClass('hide'),
$lblCount: base.Modal.Suggestion.$self.find('[data-id="SuggestCount"]'),
$listItems: function () {
return base.Modal.Suggestion.$itemContainer.find('.coll_panel_content:not([data-id="Clonable"])');
}
}
}
};
});
I'm getting Uncaught TypeError: Cannot read property '$wrapper' of undefined when you look at Google Chrome console.
Some fiddle
I tried pulling out the $wrapper and now I get new error:
Uncaught TypeError: Cannot read property 'Modal' of undefined
Another fiddle sample
I made this approach because it is more easy to manage. For example, if I have changed some class name or id on my html page, I just have to modify 1 specific variable in my jquery code and everything will be fine again. If you know a better approach, kindly share it to me.
You can't use the variable you're defining while you're defining it. So a shorter example would be:
var hi = "hi" + hi.length;
Because the variable isn't completely defined yet.
To make your code work, define the variables you need beforehand:
$(function(){
var $wrapper = $('.homepage_main'),
$modalSelf = $('#suggested_colleague'),
$itemContainer = $modalSelf.find('.request_items');
var base = {
$main: $wrapper.find('#primary').find('.home_slides').closest('[data-id="Colleague"]'),
$panel: $wrapper.find('#sidebar').find('.home_slides').closest('[data-id="Colleague"]'),
Template: {
$img: function () { return $('img'); }
},
Modal: {
$modalInterrupt: $('#searching_interruption'),
Suggestion: {
$loading: $modalSelf.find('.gif_loading'),
$paging: $modalSelf.find('.pagination'),
$itemClone: $itemContainer.find('[data-id="Clonable"]').clone().removeAttr('data-id').removeClass('hide'),
$lblCount: $modalSelf.find('[data-id="SuggestCount"]'),
$listItems: function () {
return $itemContainer.find('.coll_panel_content:not([data-id="Clonable"])');
}
}
}
};
});

Is it possible to bind to the Click event and not use an anonymous function -- I just want to call a named function

I have the following code. The first attempt at binding to click event does not work. The second way does. The first shows the alert "CheckBox1" during Page_Load. The second one shows the alert "CheckBox4" during the proper time -- during clicks.
$(document).ready(function () {
$(document.getElementById(checkBox1ID)).click( SetCheckBox1State(this.checked) );
$(document.getElementById(checkBox4ID)).click(function () { SetCheckBox4State(this.checked) });
});
function SetCheckBox1State(checked) {
alert("CheckBox2");
var radNumericTextBox1 = $find(radNumericTextBox1ID);
var wrapperElement = $get(radNumericTextBox1._wrapperElementID);
var label = $(wrapperElemenet.getElementsByTagName("label")[0]);
if (checked) {
radNumericTextBox1.enable();
label.addClass("LabelEnabled");
label.removeClass("LabelDisabled");
}
else {
radNumericTextBox1.disable();
label.addClass("LabelDisabled");
label.removeClass("LabelEnabled");
}
}
function SetCheckBox4State(checked) {
alert("CheckBox4");
var radNumericTextBox2 = $find(radNumericTextBox2ID);
var wrapperElement = $get(radNumericTextBox2._wrapperElementID);
var label = $(wrapperElemenet.getElementsByTagName("label")[0]);
if (checked) {
radNumericTextBox2.enable();
label.addClass("LabelEnabled");
label.removeClass("LabelDisabled");
}
else {
radNumericTextBox2.disable();
label.addClass("LabelDisabled");
label.removeClass("LabelEnabled");
}
}
Am I doing something improper? I'd rather not use an anonymous function...but maybe this just how things work?
This code:
.click( SetCheckBox1State(this.checked) );
Assigns the .click() function to be the output of this function: SetCheckBox1State(this.checked).
You will have to get rid of the argument (make it internal) and just pass the function name:
.click( SetCheckBox1State );

Categories