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

<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.

Related

Using a variable inside a input check in JS

The input named alternativa-*** will have the *** changed in the PHP that comes before. I'm not using a form on PHP only a onClick statement calling the respondeQuestao function. But this code seems to not work. Someone have any suggestion.
$(document).ready(function() {
function respondeQuestao(qid,resposta) {
var alternativa = document.getElementsByName('input[name = "aternativa-"' + qid ']:checked').value;
document.getElementById("demo").innerHTML = 5 + 6;
if(alternativa==resposta) {
$("#botao-questao"+qid).hide();
};
if(alternativa!=resposta) {
};
};
})
Defining a function within the jQuery Ready statement limits the accessibility - define it outside of the jQuery Ready statement but call it when you need it.
function respondeQuestao(qid, resposta) {
var alternativa = $("INPUT[name^='alternativa-']:checked").val();
$("#demo").html(5+6);
if (alternativa == resposta) {
$("#botao-questro" + qid).hide()
} else {
//
}
}
Call the function inside jQuery:
$(function() {
respondeQuestao("id", 11);
});
I hope this helps.

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.

how to pass variables to event listener method in d3

I'm working with d3, svg and AngularJS.
I've written some code to handle mouseup event on an svg element using d3. The code is as follows:
<svg>
<!-- some other code-->
</svg>
function myFunction() {
var isMouseUp = false;
d3.select("svg").on("mouseup", func1);
}
function func1() {
isMouseUp = true;
}
As you can see, isMouseUp is a local variable to myFunction().
I have to pass it to func1(). How can I do so?
P.S. I can't make isMouseUp global. Also I can't make func1() local to myFunction().
You can do this by wrapping the call to func1 in another function:
function myFunction() {
var isMouseUp = false;
d3.select("svg").on("mouseup", function() { func1(isMouseUp); });
}
function func1(isMouseUp) {
isMouseUp = true;
}
Demo here.

Calling Javascript Functions by name

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);
}
});
​

how to call a jquery / java script variable acuretly

i have #cross_1 , #cross_2 , #cross_3 , #cross_4
and every #cross_id have each #id_green
not showing any result nor any error...
var setId = 2;
var defaultTime = 3000;
$(document).ready(function () {
setLight(setId,defaultTime);
});
function setLight(setId,defaultTime) {
//deactivateAll();
activeGreen(setId,defaultTime);
}
function deactivateAll() {
$('#cross_1 #id_red').addClass('red');
$('#cross_2 #id_red').addClass('red');
$('#cross_3 #id_red').addClass('red');
$('#cross_4 #id_red').addClass('red');
}
function activeGreen(setId,defaultTime) {
alert('#cross_'+setId+ '#id_green');
$('#cross_'+setId+ '#id_green').addClass('green');
}
function activeYellow() {
//$('#cross_'+setId+ ',#id_yellow').addClass('yellow');
}
put a comma between each selector
$('#cross_'+setId+ ',#id_green').addClass('green');
I think its just your space in the jQuery selector that is in the wrong place
function activeGreen(setId,defaultTime) {
$('#cross_'+setId+' #id_green').addClass('green');
}
If your structure is:
#cross_1
#id_green
#cross_2
#id_green
And so on, which is invalid html as mentioned by others

Categories