Change the code of a javascript function - javascript

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.

Related

How to use functions parameters dynamically for CSS properties in JavaScript

I've translated some CSS code into plain JavaScript. And now i am trying to make the code a function for ease of use, but it isn't working. I know I've got it wrong, how can I make it work?
This is the CSS code
#container_show_chat {display: none;};
#container_chat {background-image: url('the url');};
In Javascript it translates to:
var a = document.getElementById("container_show_chat");
a.style.display = "none";
var b = document.getElementById("container_chat");
b.style.backgroundImage = "url('the url')";
Now what I am trying to do is, convert it into a function such that whenever i call the function I just have to add the property for the display and the url for the background image in the function call. For example:
function Practice(display, image) {
var a = document.getElementById("container_show_chat");
a.style.display;
var b = document.getElementById("container_chat");
b.style.backgroundImage;
};
Practice("none", "the url");
How can I do it?
You should assign the parameters to the elements as well. Like
function Practice(display, image) {
var a = document.getElementById("container_show_chat");
a.style.display = display;
var b = document.getElementById("container_chat");
b.style.backgroundImage = image;
};
Practice("none", "the url");
Here you have a more reusable function. Hope it helps:
<div id="container_show_chat">Hello world</div>
<script>
function setStyleInNode(nodeSelector, styleType, value) {
var node = document.querySelector(nodeSelector);
node.style[styleType] = value;
};
setStyleInNode("#container_show_chat", 'background', 'red');
</script>

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.

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

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.

Mulitple canvas-images (by Chart.js) with toDataURL()

How to handle two or more linked Canvas-Charts with Chart.js? With this script the canvas-image is linked with a bigger version to present the big file in a fancybox or just two download it (right-click -> save). Easy.
<a HREF="#" id="canvas_link_1">
<canvas id="image1"></canvas>
</a>
<a HREF="#" id="canvas_link_2">
<canvas id="image2"></canvas>
</a>
To use toDataURL() with Chart.js it's a bit tricky, cause it will render the whole chart not before the animation has ended. If we do ask for the URL too early, it will present an empty (transparent) image. That's why we need onAnimationComplete in the options:
var options = {
onAnimationComplete: done
}
Later in the script, it will fire/change the new HREF, when the animation is over.
var ct1 = document.getElementById("image1").getContext("2d");
ct1.canvas.width = document.getElementById("image1").offsetWidth;
ct1.canvas.height = document.getElementById("image1").offsetHeight;
var Chart1 = new Chart(ct1).Line(lineChartData1,options);
function done() {
var url1=document.getElementById("image1").toDataURL();
document.getElementById("canvas_link_1").href=url1;
}
var ct2 = document.getElementById("image2").getContext("2d");
ct2.canvas.width = document.getElementById("image2").offsetWidth;
ct2.canvas.height = document.getElementById("image2").offsetHeight;
var Chart2 = new Chart(ct2).Line(lineChartData2,options);
function done() {
var url2=document.getElementById("image2").toDataURL();
document.getElementById("canvas_link_2").href=url2;
}
That works. But only with one canvas-image. If I delete the 2nd function done() it will work with the 1st canvas, if I delete the 1st function, only the 2nd canvas presents the url.
I think the problem is with "done", it's not a name, just like a situation, or? The "var options" is are general for all canvas-images (for sure I can change to options1 and options2 and also to "Line(lineChartData1,options1)" but without any change)... so "done" will fire all functions and - that's bad - appearently only the last function.
On the other side I cannot rename the entry of onAnimationComplete. It's null or done, nothing else. What is to do?
You can have different callbacks with different names. "done" is just an example name (a better name would probably be "completed").
For example - first create two option objects, one for each chart:
var options1 = {
onAnimationComplete: done1
};
var options2 = {
onAnimationComplete: done2
};
Then initialize the charts with those:
...
var Chart1 = new Chart(ct1).Line(lineChartData1, options1);
...
var Chart2 = new Chart(ct2).Line(lineChartData2, options2);
And finally define the callbacks:
function done1() {
var url = document.getElementById("image1").toDataURL();
document.getElementById("canvas_link_1").href = url;
}
function done2() {
var url = document.getElementById("image2").toDataURL();
document.getElementById("canvas_link_2").href = url;
}
Hope this helps (and that I understood the problem correctly) !

How can I stop or pause one of the scripts I use when someone clicks on a specific link?

http://www.ultralocal.fr/refonte/test.php
As you can see, I have a menu with a few links. All of them, except one, launch a small script that changes the background color according to the onclick thing. The "Talweg" link work another way, it launches a bigger script that actually makes the background color change from time to time, progressively.
What I would like to know is how I can make the other links stop the Talweg script and just change the bgcolor for once.
the menu:
× Désœuvrements<br />
× Recettes<br />
× Talweg<br />
the simple script:
function changeBGC(color){
document.bgColor = color;
}
the bigger script that can be launched when one clicks on Talweg but I want to stop when one clicks on the other links.
// Set 1 dark to medium
// Set 2 light to medium
// Set 3 very dark to very light light
// Set 4 light to very light
// Set 5 dark to very dark
var fade_effect=4
// What type of gradient should be applied Internet Explorer 5x or higher?
// Set "none" or "horizontal" or "vertical"
var gradient_effect="none"
var speed=800
var browserinfos=navigator.userAgent
var ie4=document.all&&!document.getElementById
var ie5=document.all&&document.getElementById&&!browserinfos.match(/Opera/)
var ns4=document.layers
var ns6=document.getElementById&&!document.all
var opera=browserinfos.match(/Opera/)
var browserok=ie4||ie5||ns4||ns6||opera
if (fade_effect==1) {
var darkmax=1
var lightmax=127
}
if (fade_effect==2) {
var darkmax=180
var lightmax=254
}
if (fade_effect==3) {
var darkmax=1
var lightmax=254
}
if (fade_effect==4) {
var darkmax=204
var lightmax=254
}
if (fade_effect==5) {
var darkmax=1
var lightmax=80
}
var hexc = new Array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F')
var newred
var newgreen
var newblue
var oldred
var oldgreen
var oldblue
var redcol_1
var redcol_2
var greencol_1
var greencol_2
var bluecol_1
var bluecol_2
var oldcolor
var newcolor
var firsttime=true
var stepred=1
var stepgreen=1
var stepblue=1
function setrandomcolor() {
var range=(lightmax-darkmax)
if (firsttime) {
newred=Math.ceil(range*Math.random())+darkmax
newgreen=Math.ceil(range*Math.random())+darkmax
newblue=Math.ceil(range*Math.random())+darkmax
firsttime=false
}
oldred=Math.ceil(range*Math.random())+darkmax
oldgreen=Math.ceil(range*Math.random())+darkmax
oldblue=Math.ceil(range*Math.random())+darkmax
stepred=newred-oldred
if (oldred>newred) {stepred=1}
else if (oldred<newred) {stepred=-1}
else {stepred=0}
stepgreen=newgreen-oldgreen
if (oldgreen>newgreen) {stepgreen=1}
else if (oldgreen<newgreen) {stepgreen=-1}
else {stepgreen=0}
stepblue=newblue-oldblue
if (oldblue>newblue) {stepblue=1}
else if (oldblue<newblue) {stepblue=-1}
else {stepblue=0}
fadebg()
}
function fadebg() {
if (newred==oldred) {stepred=0}
if (newgreen==oldgreen) {stepgreen=0}
if (newblue==oldblue) {stepblue=0}
newred+=stepred
newgreen+=stepgreen
newblue+=stepblue
if (stepred!=0 || stepgreen!=0 || stepblue!=0) {
redcol_1 = hexc[Math.floor(newred/16)];
redcol_2 = hexc[newred%16];
greencol_1 = hexc[Math.floor(newgreen/16)];
greencol_2 = hexc[newgreen%16];
bluecol_1 = hexc[Math.floor(newblue/16)];
bluecol_2 = hexc[newblue%16];
newcolor="#"+redcol_1+redcol_2+greencol_1+greencol_2+bluecol_1+bluecol_2
if (ie5 && gradient_effect!="none") {
if (gradient_effect=="horizontal") {gradient_effect=1}
if (gradient_effect=="vertical") {gradient_effect=0}
greencol_1 = hexc[Math.floor(newred/16)];
greencol_2 = hexc[newred%16];
bluecol_1 = hexc[Math.floor(newgreen/16)];
bluecol_2 = hexc[newgreen%16];
redcol_1 = hexc[Math.floor(newblue/16)];
redcol_2 = hexc[newblue%16];
var newcolorCompl="#"+redcol_1+redcol_2+greencol_1+greencol_2+bluecol_1+bluecol_2
document.body.style.filter=
"progid:DXImageTransform.Microsoft.Gradient(startColorstr="+newcolorCompl+", endColorstr="+newcolor+" GradientType="+gradient_effect+")"
}
else {
document.bgColor=newcolor
}
var timer=setTimeout("fadebg()",speed);
}
else {
clearTimeout(timer)
newred=oldred
newgreen=oldgreen
newblue=oldblue
oldcolor=newcolor
setrandomcolor()
}
}
Thanks
The longer-running script keeps re-executing itself with selfTimeout. If you want to stop it, all you need to do is call clearTimeout on the returned variable:
clearTimeout(timer)
Of course, you may need to be a bit more careful, because the script may be in the middle of the execution when you clear the timeout. One way to deal with it would be to set a flag indicating that the script need not be re-executed again. You can pull variable declarations out of the functions to make the code easier to read. So your code can look like this:
//variable declaration for use in fadebg function
var timer;
//variable declaration for the flag
var contBg = true;
//stop your previous script
function stopRandomBg() {
clearTimeout(timer);
contBg = false;
}
//changes to fadebg function
function fadebg() {
...
//change this line
//var timer=setTimeout("fadebg()",speed);
//to
if(contBg) {
timer=setTimeout("fadebg()",speed);
}
...
}
These additional changes will take care of the case when the script is in the middle of execution when you try to stop it - it will complete the execution pass and then stop.
Now all you need to do is to add onClick event listener to your link to call stopRandomBg function.
You have to make the timer variable global instead of local.
var timer;
then clear the timer when ever you call other links.
function changeBGC(color){
clearTimeout(timer);
document.bgColor = color;
}

Categories