What's Wrong With My Javascript Code? It Won't Run - javascript

var malediv = document.querySelector('.male');
var femalediv = document.querySelector('.female');
var male_sources = [
"/images/m1.png",
"/images/m2.png",
"/images/m3.png",
"/images/m4.png",
"/images/m5.png",
"/images/m6.png",
"/images/m7.png",
"/images/m8.png",
]
var female_sources = [
"/images/f1.png",
"/images/f2.png",
"/images/f3.png",
"/images/f4.png",
"/images/f5.png",
"/images/f6.png",
"/images/f7.png",
"/images/f8.png",
]
function displayRandMaleImage() {
malediv.innerHTML = "";
var malerandom_number = Math.floor(Math.random() *
male_sources.length);
var random_male_image_source = male_sources[malerandom_number];
maleimg = document.createElement('img');
maleimg.setAttribute('src', random_male_image_source);
malediv.append(maleimg);
alert('maleimagedisplayed');
}
function displayRandFemaleImage() {
femalediv.innerHTML = "";
var femrandom_number = Math.floor(Math.random() * female_sources.length);
var random_female_image_source = female_sources[femrandom_number];
femaleimg = document.createElement('img');
femaleimg.setAttribute('src', random_female_image_source);
div.append(femaleimg);
}
function displayRandImages(){
displayRandMaleImage();
displayRandFemaleImage();
alert('SKEEET');
}
none of my display random image fundtions are working in my html page that this is embedded in. I even added a test function "anAlert" that works perfectly. Please help me to understand what i can do to make this work.

There are two reasons why it isn't working.
1) You haven't defined the button. Which should've been done like:
var button = document.querySelector('.button_class');
or using the id:
var button = document.getElementById('button_id');
2) Your function to call the other two display functions is named displayRandImages()
function displayRandImages(){
displayRandMaleImage();
displayRandFemaleImage();
alert('SKEEET');
}
whereas, you've used the function displayRandomImage() in your click event:
button.addEventListener('click', displayRandomImage);
displayRandImages() != displayRandomImage()

button is not defined
button.addEventListener('click', displayRandomImage);
You should use it like
document.getElementById('buttonid').addEventListener('click', displayRandImages);
where 'buttonid' is id of your button, should be defined in html.
One more thing, as you are accessing button outside any other js function, So it'll be called on page load.
So you have to write this javascript after your html code so that it'll be called after button element rendered in HTML.

Related

Why my html element is not shown in the following function

my goal is to display a loading curtain when a query to Quick-Base takes too long.
I have the following code that I thought it was going to work but it somehow does not. Everything works except for the loading curtain because it is never executed when it should be.
My code:
<script>
window.onload = function(){
// .. more code here not related ...
function selectedValueChanged() {
$('#curtain').show();
var e = document.getElementById("record_id_select");
var value_selected = e.value;
var CO_picked_record_id = parseInt(value_selected);
var query_CO_line_details = "{'"+related_CO_fid+"'.EX.'"+CO_picked_record_id+"'}";
var records = getRecords(table_CO_line_details_DBID,query_CO_line_details);
var data_array = createArrayFromRecordsDrilled(records,CO_detail_record_categories);
var table_div = tableCreate(data_array,'table_container_1',"Please Enter Quantities",headerList);
$('#table_container_1').replaceWith(table_div);
$('#curtain').hide();
}
}
</script>
<div id='curtain' style='position:absolute;top:0;left:0;margin:0;background:rgba(255,255,255,.3); display:none; width:100%;height:100%;'><img id ="loading_text" src="loader.gif"></div>
</body>
The code works but the curtain is never shown even if the query takes a couple of seconds (as much as 6 seconds). If I comment out the line "$('#curtain').hide();" I can see the loading curtain working as expected but only after the query has finished. It is as if the function is not been executed line by line but it waits first to complete the query and then to show the curtain. I'm sure I'm missing something but I don't know what. Thank you.
use this instead(no need to add any HTML to page) :
function showLoading() {
if (document.getElementById("loadingDiv"))
return;
var div = document.createElement("div");
var img = document.createElement("img");
var span = document.createElement("span");
span.appendChild(document.createTextNode("Loading ..."));
span.style.cssText = "margin-top:50vh;font-family:IranSans;direction:rtl;color:#f78d24;"
img.src = "/images/LoadingImage.png";
img.style.cssText = "display:block;margin:auto;margin-top:calc(50vh - 64px);width:128px;height:128px;"
div.style.cssText = "position:fixed;width:100vw;height:100vh;background-color:rgba(0,0,0,0.85);top:0px;left:0px;z-index:10000;text-align:center";
div.id = "loadingDiv";
div.appendChild(img);
div.appendChild(span);
document.body.appendChild(div);
}
function hideLoading() {
var div = getElementById("loadingDiv");
if (div)
document.body.removeChild(div);
}
The solution as #keith suggested was to "transform" the getRecords function from synchronous to asynchronous.
I ended up making the whole function selectedValueChanged() "asynchronous" by using the setTimeout trick.
One solution that worked for me was the following:
function selectedValueChanged() {
var e = document.getElementById("record_id_select");
var value_selected = e.value;
var CO_picked_record_id = parseInt(value_selected);
var query_CO_line_details = "{'"+related_CO_fid+"'.EX.'"+CO_picked_record_id+"'}";
var records = getRecords(table_CO_line_details_DBID,query_CO_line_details);
var data_array = createArrayFromRecordsDrilled(records,CO_detail_record_categories);
var table_div = tableCreate(data_array,'table_container_1',"Please Enter Quantities",headerList);
$('#table_container_1').replaceWith(table_div);
}
}
function loadingSelectedValueChanged(callbackFunct){
setTimeout(function(){
callbackFunct()
$('#curtain').hide();
},10);
}
function selectedValueChangedUP() {
$('#curtain').show();
loadingSelectedValueChanged(selectedValueChanged);
}
And now instead of calling selectedValueChanged, I call selectedValueChangedUP.
What SetTimeout does is to execute the function that receives as parameter after a given amount of time. This process is done in an "asynchronous" way.

Swap images with onclick

I have an incomplete script here that just needs to give a few adjustments of positions and add the exchange of images with the function Onclick of JavaScript but do not remember how to do more this exchange I would like to know what the error of the following code and how to fix, since I thank you.
// Like Normal e like Marcado
var imgLike01 = "images/mylike.png"
var imgLike02 = "images/like.png"
// Deslike Normal e deslike desmarcado
var imgDeslike01 = "images/mydeslike.png"
var imgDeslike02 = "images/deslike.png"
var likebtn = document.getElementById("likebtn");
var deslikebtn = document.getElementById("deslikebtn");
function like () {
likbtn.img.src = imgLike02;
}
function deslike () {
deslikebtn.img.src = imgDeslike02;
}
function Trade(){
if ($like).click(function() {
likbtn.img.src = imgLike01;
});
if ($deslike).click(function() {
deslikebtn.img.src = imgDeslike01;
});
}
Note This is the exchange of images from an old like system in JavaScript, a sum script and only missing image switching.
Add an eventListener to likebtn:
likebtn.addEventListener("click", like);
Do the same for deslikebtn.

Changing multiple images source using jquery (and some other thing as well)

I am a beginner of javascript and jquery and i have 11 image tags in html. I want to
basically change sources of these tags using js and jquery. This code is not working and I am not getting any errors in firebug, can some one please tell me where I am doing wrong?
var imagesArray2=["01.png","02.png","03.png","04.png","05.png","06.png","07.png","08.png","09.png","10.png","11.png"];
var elementArray2 = ["#img1","#img2","#img3","#img4","#img5","#img6","#img7","#img8","#img9","#img10","#img11"];
var imagesArray,elementArray;
var elementInArray;
document ready
$(function(){
setInterval(Myfunction(),1000);});
my function code which has a loop based on elementsInArray variable value and it calls imageFadeAnimations function
function Myfunction(){
if(elementsInArray === 0){
imagesArray = imagesArray2;
elementArray = elementArray2;
elementsInArray = elementArray.length;
var imageChanges = Math.floor(Math.random()*elementsInArray);
imageFadeAnimations(imageChanges);
}
else
{
elementsInArray=elementArray.length;
imageChanges = Math.floor(Math.random()*elementsInArray);
imageFadeAnimations(imageChanges);
}
}
takes an integer as argument
function imageFadeAnimations(imageChanges){
for(var k = 0;k<imageChanges;k++){
var element = Math.floor(Math.random()*elementsinArray);
var image=Math.floor(Math.random()*elementsinArray);
imageChanger(elementArray[element],imageArray[image]);
elementArray.splice(element,1);
imagesArray.splice(image,1);
}
}
function imageChanger(b1,b2){
$(b1).fadeOut(500,function(){
$(b1).attr("src",b2);
$(b1).fadeIn(500);
});
}
You are making heavy weather out of something that jQuery can make very simple.
First wrap your images in an element (typically a div or a span) with id="imageContainer".
Now, if I understand correctly, your code will simplify to :
$(function() {
var imagesArray = ["01.png", "02.png", "03.png", "04.png", "05.png", "06.png", "07.png", "08.png", "09.png", "10.png", "11.png"],
$images = $("img", "#imageContainer");
setInterval(function() {
$images.each(function() {
var $img = $(this),
i = Math.min(imagesArray.length-1, Math.floor(Math.random() * imagesArray.length));
$img.fadeOut().promise().then(function() {
$img.attr("src", imagesArray[i]).fadeIn(500);
});
});
}, 1000);
});
EDIT 1
As #mplungjan points out below ...
If the img nodes were initialised with src attributes, then imagesArray can be composed by grabbing the srcs from the DOM as follows (replacing two lines above) :
var $images = $("img", "#imageContainer"),
imagesArray = $images.map(function() { return this.src; }).get();
I believe this jquery/zepto code is not the smaller, but the easier to understand:
function changeImg(){
$("#img1").attr('src', '01.png');
$("#img2").attr('src', '02.png');
$("#img3").attr('src', '03.png');
$("#img4").attr('src', '04.png');
$("#img5").attr('src', '05.png');
$("#img6").attr('src', '06.png');
};

Change the code of a javascript function

Actually my idea is the following: i have a div tag that displays the result of a function called "afficher_general()" inside a script tag, and a button that calls a first function called "Ajouter_general()" that's supposed to change a string inside the function "afficher_general()"
var general = document.getElementById("general");
general.innerHTML = general.innerHTML.replace('//WRITE', ch);
the button is as follows:
<input type="button" value="ajouter au graphe general" id="id1" onClick="Ajouter_general();afficher_general();" />
But this doesn't seem to work because i've been told that a script is loaded only once and it cannot be changed. So is there any solution ? Thanks in advance.
So i'll add what contain the functions. Actually i'm working with Amcharts . the function afficher_generalis as follows:
<script name="general" id="general" type="text/javascript">
function afficher_general()
{
chart = new AmCharts.AmSerialChart();
chart.dataProvider = chartData;
chart.categoryField = "country";
chart.startDuration = 1;
// WRITE
chart.write("chartContainer");
}
</script>
instead of the comment //WRITE i wish to add the a code everytime the button is pressed. the function is as follows:
function Ajouter_general(ind){
var ch="";
var couleur = getSelectValueId("background-color"+ind);
var transparence = getSelectValueId("transparence"+ind);
var type = get_radio_value_type(ind);
var balloon = getSelectValueId("balloon-color"+ind);
if(type == "column")
{
ch=ch+"var graph"+ind+" = new AmCharts.AmGraph();";
ch=ch+"graph"+ind+".valueField = "+"visits"+";"
ch=ch+"graph"+ind+".balloonColor = "+balloon+";";
ch=ch+"graph"+ind+".type = "+type+";";
ch=ch+"graph"+ind+".fillAlphas = "+transparence+";";
ch=ch+"graph"+ind+".fillColors = ["+couleur+"];";
ch=ch+"graph"+ind+".lineColor = ["+couleur+"];";
ch=ch+"chart.addGraph(graph"+ind+");";
ch=ch+"// WRITE";
}
var general = document.getElementById("general");
general.innerHTML = general.innerHTML.replace('//WRITE', ch);
}
since Amcharts uses the script to draw graphs inside a chart, i would like to be able to dynamically add those graphs everythime the button is pressed.
If you really need to change the definition of a function, you could always just redefine it (functions are just objects assigned to variables):
var Ajouter_general = function () {
// redefine the afficher_general function
afficher_general = function () {
// change it to whatever you want
};
};
That being said, this is generally a bad practice and the same functionality can be better accomplished by using function parameters.

New to JavaScript and need help on my first program

I'm trying to add a function to my website so when the user clicks on a footnote the browser will display it inline. Here is how far I have gotten,
var locate= document.getElementById("footnote1");
var note= document.getElementById("footnotes2");
function footnote() {
locate.onclick= note.style.display="inline";
};
any help would really be appreciated.
Here is an example of what you want.
var locate = document.getElementById("footnote1");
var note = document.getElementById("footnotes2");
locate.onclick = function() {
note.style.display = "inline";
};
Working Example
http://jsfiddle.net/v8fHE/
you just had to wrap the onclick action in a function
trigger.onclick=function(){toChange.style.background="#FF0000"};

Categories