Trying to get some buttons do the same thing - javascript

I am using Animate to create an animation. I am on the process of getting all the buttons to do what they are supposed to. Right now, I am stuck with the following. I would like to assign multiple buttons the same action, this is because the buttons appear on many different frames, so this is what I have got but I am getting an error.
var btns = ["btncasco","btncasco1","btncasco2"];
btns.forEach( btnsIteratee.bind(this));
function btnsIteratee(item){
this[item].addEventListener("click", function(event){
this.gotoAndStop(0);
});
}
I want to be able to click on any of the referenced button names and make them go to frame 0. Any idea about of what is wrong?
This is the error I get:
"Uncaught TypeError: Cannot read property 'addEventListener' of undefined"

It's a little hard to tell from the small amount of code you have provided what else is going on that could cause unexpected behaviour of this. However. The following:
btns.forEach( btnsIteratee.bind(this));
Could benefit from being bound once, as the reference to this won't change for each instance of the forEach loop. Then having the array item passed in. Something like:
var btns = ["btncasco", "btncasco1", "btncasco2"];
function btnsIteratee(item) {
item.addEventListener("click", function(event) {
this.gotoAndStop(0);
});
}
btnsIteratee = btnsIteratee.bind(this);
btns.forEach(btnsIteratee);
The above is pseudo code as there isn't much provided by your example

thanks for the posts. I finally sorted this out using this chunk of code for each series of buttons.
var btntres = ['btnlumbrera2' , 'btnlumbrera3' ,'btnlumbrera4' ,'btnlumbrera5' ,'btnlumbrera6' ,'btnlumbrera7', 'btnlumbrera8', 'btnlumbrera9', 'btnlumbrera10', 'btnlumbrera11', 'btnlumbrera12', 'btnlumbrera13', 'btnlumbrera14', 'btnlumbrera15', 'btnlumbrera16', 'btnlumbrera17', 'btnlumbrera18'];
btntres.forEach( btnsIteratee3.bind(this) );
function btnsIteratee3(item){
if (this[item] && !this[item].hasEventListener('click')) {
this[item].addEventListener("click", hyandler.bind(this));
} else {
console.log('item no existe', item);
}
function hyandler(event){
this.gotoAndStop(4);
}
}

Related

Kendo controls don't seem to be ready in document.ready

I am using the kendo kendoNumericTextBox.
The kendo js libraries are included before the following.
I am trying to store a reference to the actual input for later use like this:
$(document)
.ready(function () {
//Wire up the elemets with selectors
$eventGrid = $("#jsGrid");
$bedInput = $('#bed');
$dateInput = $('#date');
$operatingTimeInput = $("#operatingTime").data("kendoNumericTextBox"); <-- ERROR OCCURS HERE
$plannedDowntimeInput = $("#plannedDowntime").data("kendoNumericTextBox");
fetchDayData(currentBed(), currentDate());
})
Uncaught TypeError: Cannot read property 'value' of undefined
However when stepping through, both $operatingTimeInput and $plannedDowntimeInput are undefined. If I later do these assigments manually in the console, everything works as expected.
Now, I seem to remember there being an event similar to document.ready() but specifically for kendo. Though, For the life of me, I can't find it...
Any thoughts?
EDIT 1
The fields are being initialized in a razor view like this:
#(Html.Kendo().NumericTextBox()
.Name("operatingTime")
.Max(24)
.Min(0)
.Step(0.05)
.HtmlAttributes(new { #id = "operatingTime" })
)
So as you can see, I have no control over when the textbox is actually "created". That's why I'm looking for a way to get the instance created by the html helper.
One way which I tried to accomplish is like :
$(document)
.ready(function () {
$("#operatingTime").ready(function(){
setTimeOut(function(){
if($("#operatingTime").data("kendoNumericTextBox")){
//Wire up the elemets with selectors
$eventGrid = $("#jsGrid");
$bedInput = $('#bed');
$dateInput = $('#date');
$operatingTimeInput = $("#operatingTime").data("kendoNumericTextBox"); <-- ERROR WILL NOT OCCUR HERE
$plannedDowntimeInput = $("#plannedDowntime").data("kendoNumericTextBox");
fetchDayData(currentBed(), currentDate());
}
},1000);
});
})
Since I had comfort of waiting for 1 second, I went with this logic. let us know if something else has worked out for you.

Looping through multiple checkboxes and adding the checked values to an array to write back to Sharepoint

I have a block of code that is supposed to look at which checkboxes are checked and then write the value of those checkboxes to an array so that I can write the data back to Sharepoint. I got it working before when I used an if/else statement, but I need it to be able to handle multiple checkboxes being selected. I did some research and found part of my code from another answer and combined it with some of my code but it doesn't seem to be working and I'm not sure why. None of the other answers I came across seem to be what I'm looking for.
Basically, what I'm asking is, what is the best way to achieve what I'm trying to do?
function addCustomers() {
$(document).ready(function () {
var customers = [];
var ckbox = $('.customer-options');
$('input').on('click', function () {
if (ckbox.is(':checked')) {
customers.push(ckbox).val();
}
else {
}
});
customers.toString();
document.getElementById('mxID04').innerHTML = customers;
});
}
It's not exactly clear what you are trying to do. First, your function contains document.ready which doesn't look right. Then you create some vars which I think you want to fill because at the end you are setting another element's innerHTML to, but in between you've just created a click handler which isn't going to work. Here's what I've put together for testing. I think you should be able to modify my example into what it is you're after
function addCustomers() {
var customers = [];
var ckbox = $('.customer-options');
alert('add handler');
$('input').change(function() {
$('input:checked').each(function() {
customers.push(this);
});
});
}
$( document ).ready(function() {
// alert('here');
addCustomers();
});

How can I add a link to dynamically created button?

Once the buttons are created, is there anyway I can add a link or use window.location method like this: `window.location = 'nextpage.html?foo=number'. I currently have this
var typeValue = location.search;
var typeStringValue= typeValue.replace("?type=","");
var containers = typeValue.replace("?type=multi","");
var containersValue = parseInt(containers);
var sampleLetter = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
function createButton(buttonName){
var buttonDivBlock = document.getElementById("sampleSets");
var buttonElement = document.createElement("input");
buttonElement.setAttribute("type","button");
buttonElement.setAttribute("name",buttonName);
buttonElement.setAttribute("value","Sample Set"+" "+buttonName);
buttonElement.setAttribute("id",buttonName);
buttonDivBlock.appendChild(buttonElement);
// document.getElementById(sampleLetter[i]).setAttribute('onclick',window.location='SampleInfo.html'+typeStringValue+bottonName);<!--add the button link -->
}
function setButtons(numberOfContainers){
for(i=0;i<numberOfContainers;i++){
createButton(sampleLetter[i]);
}
}
window.onload = function(){
setButtons(containersValue);
}
But document.getElementById("'"+sampleLetter[i]+"'").setAttribute('onclick',window.location='SampleInfo.html'+typeStringValue+bottonName);<!--add the button link -->
returns a null value.
Well, maybe I can help you along with an example:
function getFive() { return 5;}
callOtherFunction("stringArgument", getFive());
The second argument to callOtherFunction is going to be 5, not the getFive function. In many cases, like adding event listeners and AJAX code, you actually want to pass the function itself as an argument, so it can be called later. But if you don't want to bother declaring that function seperately, it looks like this:
callOtherFunction("stringArgument", function() { return 5; });
To make code look cleaner, you can press Enter after the { and make a multi-line function.
Now, all that in mind, take another look at the line you've commented out. Do you see what's missing? (PS. Apologies for the "egging-on" format - I find people get much better at figuring things out if I help them find the solution, rather than just showing it to them)
The sampleLetter variable is not defined where you are trying to use it (judging by commented code). Use the value you had just set to the id attribute a few lines earlier.
document.getElementById(buttonName).setAttribute( /* ... */ );
Or if you are trying to set it in the loop instead of in the createButton function, do not add the single quotes
document.getElementById(sampleLetter[i]).setAttribute( /* ... */ );

JavaScript two onload functions

I am quite new to JavaScript programming and I'm trying to create some scripts that would save me time in maintaining one of my websites.
Now I have two functions in the same script that I'm calling from the head of my document and I'm trying to get them both to load at the same time with an onload event handler. I am doing that with window.onload command in my script (I want to make my script as unobtrusive as possible so I'm just calling the script in the header).
The problem is that only the first function loads and the second one doesn't. Can both functions be called with:
window.onload=function(){
function1();
function2();
}
or is there a different code I need to use to accomplish this?
I would really appreciate it if you could make your explanations as simple as possible as I am very new to JavaScript and programming in general.
P.S. If more than one function can't be loaded with onload, could you please explain to me why this is the case so I know in the future.
Ok, I see by the answers that my question probably left too much for assumption so here is the entire code of the functions I am trying to call (this is the script I am calling in the head of my html document):
I was trying to avoid putting the code here because my variables are written in Serbian language (as I am from Serbia), but I hope that you will still be able to look through it without much confusion.
In the code below I am calling at the bottom of the script two functions (lista() and ostale()) and the moveover() function is just a helper function called by the lista() function.
In essence the first one (lista()) lists through all elements of div "boje" (in English translated to "colors") and depending on the color the user hovers their mouse over, the background image changes. It also adds a few attributes to those image elements that the user is supposed to hover over.
The second one (ostale() (Translated to English "others") is supposed to only add attributes to the rest of the color images that are not supposed to do anything if the user hovers over them.
But when I open the page in localhost it doesn't show in Firefox's inspect element that any attributes have been added to the images within the div "ostale".
function lista()
{
var boje = document.getElementById('boje');
var broj = boje.childNodes.length;
for(i=1; i<broj; i++)
{
var stavka = boje.childNodes.item(i);
stavka.setAttribute("id", i);
stavka.setAttribute("onmouseover", "moveover(src)");
stavka.setAttribute("alt", "Boja");
stavka.setAttribute("class", "boja");
stavka.hspace="2";
stavka.height="23";
}
}
function moveover(adresaBoje)
{
var izvor = adresaBoje;
var slika = izvor.slice(0, izvor.length-4);
var pocetak = "url(";
var ekstenzija = ".jpg)";
var novaSlika = pocetak.concat(slika, ekstenzija);
document.getElementById('slika').style.backgroundImage=novaSlika;
}
function ostalo(){
var ostaleboje = document.getElementById('ostale');
var ostalebroj = ostaleboje.childNodes.length;
for(n=1; n<ostalebroj; n++)
{
var ostalestavka = ostaleboje.childNodes.item(n);
ostalestavka.setAttribute("alt", "Boja");
ostalestavka.hspace="2";
ostalestavka.height="23";
}
}
window.onload=function(){
try
{
lista();
ostalo();
}
catch(err)
{
alert(err);
}
}
After I try to load the page it alerts me with an error: "TypeError: stavka.setAttribute is not a function".
This is the html document I am trying to manipulate:
<div id="slika" style="background-image: url(images/nova_brilliant/1.jpg)">
</div>
<div id="tekst">
<h1>Nova Brilliant</h1>
<div id="sadrzaj">
<p>Pređite mišem preko željene boje da biste videli kako izgleda ova kuhinja u toj boji:</p>
<div id="boje">
<img src="images/nova_brilliant/1.gif"><img src="images/nova_brilliant/2.gif"><img src="images/nova_brilliant/3.gif">
</div>
<p>Ostale dostupne boje:</p>
<div id="ostale">
<img src="images/nova_brilliant/4.gif"><img src="images/nova_brilliant/5.gif"><img src="images/nova_brilliant/6.gif">
</div>
</div>
</div>
I ran into the same problem. I came across a couple of help but this one was easy to understand and it worked for me:
window.addEventListener("load", func1); window.addEventListener("load", func2);
just like #Quentin You can read more about it here
Yes you can. However, if the first goes wrong, the second won't fire.
Use this to catch errors:
try { //try executing the functions
function1();
function2();
}
catch(error) { // If there's an error
alert(error); // alert the error.
}
It is a good practice to put try and catch when experimenting with javascript.
Edited: Sorry i confused childNodes[] with childNodes.item().
By the way, I tried something like this, and it works just fine:
<head>
<script>
window.onload = function() {
div = document.getElementById("someDiv");
length = div.childNodes.length;
first();
second();
}
function first() {
for(var i=0;i<length;i++) {
var set = div.childNodes.item(i);
set.setAttribute("name", "span " + (i+1));
}
}
function second() {
for(var i=0;i<length;i++) {
name = div.childNodes[i].getAttribute("name");
console.log(name);
}
}
</script>
</head>
<body>
<div id='someDiv'><span id='span1'></span><span id='span2'></span></div>
</body>
UPDATE: I found the error:
Actually there's nothing wrong with your code. It works just fine, however, the last item of boje is empty space, which means, a text node. That's why the error keeps showing up. Change for(i=1; i<broj; i++) with for(i=1; i<broj-1; i++) and everything should be good.
Can both functions be called with
Yes. If you add event handlers by assigning to DOM properties, then you can only assign a single function to each but that function can call other functions.
However, if you do that and the first function throws an error then the second function won't fire at all. It will also discard the context and arguments, as they won't be passed to the called functions.
You could work around those problems like so:
window.onload=function(){
try {
function1.apply(this, arguments);
} catch (e) { }
try {
function2.apply(this, arguments);
} catch (e) { }
}
or is there a different code I need to use to accomplish this?
You should use addEventListener instead. That avoids the need to fiddle with apply, and protects you from errors being thrown. See the MDN events documentation for more details.
window.addEventListener('load', function1);
window.addEventListener('load', function2);

JQuery not a function error

While developing with Firebug I keep getting this error.
pages[x].css("z-index",x) is not a function
The function itself works fine but I'm trying to figure out why it keeps flagging this. The function is simultaneously reorganizing the array and the z-indexes.
Can i not access array variables and call functions on them like this or is this something else?
full code:
var pages = $("#use-wrapper").children("div");
pages.children("a.right").click(function(event) {
event.preventDefault();
$(this).parent("div").css("z-index","0");
pages.push($(this).parent("div"));
for(var x = pages.length; x >= 1; --x) {
pages[x] = pages[x-1];
pages[x].css("z-index",x);
}
pages[0] = pages.pop();
});
If you do an alert(pages[x]), you'll find that each pages[x] is a DOM element and not a jQuery object, which is why you get the error that pages[x].css is not a function. You probably want to do:
$(pages[x]).css('z-index', x);
Edit: Even though jQuery lets you access the elements of pages as though it's an array, it's not a true array object, so I doubt that push and pop will work too.

Categories

Resources