I'm a quite new in javascript, and I'm trying to do a script to get a soft color change, bbut when a call the objetc to be changed, I got some problems. My code is this:
<script lenguage="javascript">
hexadecimal = new Array("0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F")
function convierteHexadecimal(num){
var hexaDec = Math.floor(num/16)
var hexaUni = num - (hexaDec * 16)
return hexadecimal[hexaDec] + hexadecimal[hexaUni]
}
function convierteHexadecimal(num){
var hexaDec = Math.floor(num/16)
var hexaUni = num - (hexaDec * 16)
return hexadecimal[hexaDec] + hexadecimal[hexaUni]
}
color_decimal=0
function degradado(){
color_decimal ++
color_hexadecimal = convierteHexadecimal(color_decimal)
document.getElementById("title").style.color = color_hexadecimal + color_hexadecimal + color_hexadecimal
//la llamo con un retardo
if (color_decimal < 255)
setTimeout("degradado()",1)
}
degradado()
this is my code, but when I load it in chrome, an issue appears in:
document.getElementById("title").style.color
My h1 is:
<h1 align="center" id="title">Degradando...</h1>
I notice the id is correctly write, So, what is the problem?
Try to do this:
window.onload = function(){
document.getElementById("title").style.color
}
I think you are accessing the element even before it is created.
Call your function from the onload handler:
window.onload = function() {
degradado();
}
so that it will run after the DOM is loaded.
Related
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.
I have a simple image rotator on a website consisting of 4 images that have to appear for a few seconds before showing the next one. It seems to work on its first cycle but then when it gets back to the first image it doesn't show that one but works again from the second image and so on always missing that image on every cycle.
The function is called using onLoad EH in the body. In the body there is an img with my first image inside it. I'm a noob so please be gentle if I've missed anything out.
Here's what I have...
<body onLoad="sunSlideShow()">
<img src="IMAGES/slider1.gif" alt="slide-show" id="mySlider" width="900">
<body>
var quotes = new Array ("slider2.gif", "slider3.gif" ,"slider4.gif", "slider1.gif");
var i = 0
function sunSlideShow()
{
document.getElementById("mySlider").src = ( "IMAGES/" + quotes[i] );
if (i<4)
{
i++;
}
else
i = 1;
setTimeout("sunSlideShow()", 3000);
}
sunSlideShow()
Change it to this:
else
i = 0;
setTimeout("sunSlideShow()", 3000);
Further to my other answer (which was wrong!)... Try this:
http://jsfiddle.net/pq6Gm/13/
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
setInterval(sunSlideShow,3000);
});
var quotes = [
"http://static.guim.co.uk/sys-images/Guardian/Pix/pictures/2007/07/11/sun128.jpg",
"http://icons.iconarchive.com/icons/robinweatherall/seasonal/128/sun-icon.png",
"http://www.astronomytoday.com/images/sun3.gif",
"http://mariusbancila.ro/blog/wp-content/uploads/2011/08/sun.png"
];
var i = 0;
function sunSlideShow() {
document.getElementById("mySlider").src = quotes[i];
if (i < (quotes.length-1))
{
i++;
}
else
{
i = 0;
}
}
</script>
<body>
<img src="http://mariusbancila.ro/blog/wp-content/uploads/2011/08/sun.png" id="mySlider"/>
</body>
==================================================================
EDIT: This is wrong... please find my other answer on this page.
==================================================================
To start with, I wouldn't use ... you're better off starting the script with jquery once the page is loaded.
Add this to your head section:
<script type="text/javascript">
$(function () {
sunSlideShow();
}
</script>
That will fire the sunSlideShow function once the page is loaded.
Then, you're starting your slideshow with var i = 0... but when you've got to the fourth image, you're setting it to 1?
I would be tempted to use a while loop to achieve what you want.
Something like this:
<script type="text/javascript">
$(function () {
sunSlideShow();
}
var quotes = new Array ("slider2.gif", "slider3.gif" ,"slider4.gif", "slider1.gif");
var i = 0;
function sunSlideShow(){
while (i<4)
{
document.getElementById("mySlider").src = ( "IMAGES/" + quotes[i] );
if (i<4)
{
i++;
}
else
{
i = 0;
}
sleep(3000);
}
}
function sleep(miliseconds){
var currentTime = new Date().getTime();
while (currentTime + miliseconds >= new Date().getTime()){}
}
</script>
This script hasn't been tested... but it should start the sunSlideShow function once the page has loaded and then change the image every 3 seconds.
I too searched the web trying to find a general solution to the problem of rotating an image about its center. I came up with my own solution which works perfectly. The basic concept is simple: rotate the entire context by the desired angle (here called 'tilt'); calculate the image's coordinates in the NEW coordinate system; draw the image; lastly, rotate the context back to its original position. Here's the code:
var xp = rocketX * Math.cos(tilt) - rocketY * Math.sin(tilt);
var yp = rocketX * Math.sin(tilt) + rocketY * Math.cos(tilt);
var a = rocketX - xp;
var c = Math.sqrt(a*a + (rocketY-yp)*(rocketY-yp));
var beta = Math.acos(a/c);
var ap = c * Math.cos(tilt + beta);
var bp = c * Math.sin(tilt + beta);
var newX = rocketX + ap;
var newY = rocketY - bp;
context.rotate(tilt);
context.drawImage(littleRocketImage, newX-9, newY-40);
context.rotate(-tilt);
In the penultimate line, the constants '9' and '40' are half the size of the image; this insures that the rotated image is placed such that its center coincides with the center of the original image.
One warning: I use this only for first quadrant rotations; you'll have to put in the standard tests for the other quadrants that change the signs of the components.
Update: 2021
You can use the light-weight library Ad-rotator.js to setup simple Ad-rotation like this -
<script src="https://cdn.jsdelivr.net/npm/ad-rotator"></script>
<script>
const instance = rotator(
document.getElementById('myelement'), // a DOM element
[ // array of ads
{ url: 'https://site1.com', img: 'https://example/picture1.jpg' },
{ url: 'https://site2.com', img: 'https://example/picture1/picture2.jpg'},
// ...
]
);
</script>
<body onLoad="instance.start()">
<div id="myelement"></div>
<body>
Reference Tutorial
I am implementing a Stopwatch in JavaScript.
I want to delete additional div elements when pushing a clear button. I added function cc();, but function cc() doesn't work. What's wrong with my code?
Javascript:
a = 0;
myButton = 0;
function myWatch(flug) {
if(myButton == 0) {
Start = new Date();
myButton = 1;
document.myForm.myFormButton.value = "Stop!";
myInterval = setInterval("myWatch(1)", 1);
} else {
if(flug == 0) {
myButton = 0;
document.myForm.myFormButton.value = "Start";
clearInterval(myInterval);
}
Stop = new Date();
T = Stop.getTime() - Start.getTime();
H = Math.floor(T / (60 * 60 * 1000));
T = T - (H * 60 * 60 * 1000);
M = Math.floor(T / (60 * 1000));
T = T - (M * 60 * 1000);
S = Math.floor(T / 1000);
Ms = T % 1000;
document.myForm.myClick.value = H + ":" + M + ":" + S + ":" + Ms;
}
}
b = 0;
function stop() {
b++;
stopa();
}
function stopa() {
var element = document.createElement('div');
element.id = pos;
var objBody = document.getElementsByTagName("body")
.item(0);
objBody.appendChild(element);
rap = "";
rap = "rap" + b + "=" + H + ":" + M + ":" + S + ":" + Ms;
element.innerHTML = rap;
}
function cc() {
document.body.removeChild(element);
}
HTML:
<form name="myForm" action="#">
<input type="text" size="20" name="myClick">
<input type="button" value="Start" name="myFormButton" onclick="myWatch(0)" />
<input type="button" value="Rap" name="Rap" onclick="stop()">
<input type="button" value="clear" name="clear" onclick="cc()">
</form>
<h3>
<div id="pos">
</div>
</h3>
Try to pass the context explicitly as parameter on the cc() function.
js
function cc(el) {
el.parentNode.removeChild(el);
}
html
<input type="button" value="clear" name="clear" onclick="cc(this)">
Open up your Console. It's found in most major browsers and will help you loads with JS development.
For example, if you look at your code exactly as is, you get an error:
Uncaught ReferenceError: element is not defined
As several have said, it's a variable scope issue. There's a few easy fixes, the easiest being simply making element have a larger scope - that is, define it outside of your functions first.
var element = null;
and then in stopa, don't use var because it'll make a new, local variable instead of using the global one.
element = document.createElement('div');
The next problem you'll notice is that element in cc still doesn't refer to the correct element - this is because in the following line, pos is not defined.
element.id = pos;
Again, take a look at the Console (now more specifically at the HTML section than the JS, but it's in the same developer options). You'll notice the created element's ID is [object HTMLDivElement] - not "pos". I'd recommend not even worrying about giving them ids, you have a div with id pos already in your HTML, simply append your results to that instead of the body.
objBody = document.getElementById("pos");
Then when you clear, clear all children from pos (you'll also want to clear the text box I'm sure, so here ya go)
while (objBody.hasChildNodes()) {
objBody.removeChild(objBody.lastChild);
}
document.myForm.myClick.value = "";
Notice now we no longer need element to be global, because it's only referenced in one function - it can be local to that function. However, objBody is now referenced in stopa and cc, so we'll make it global as we did with element and simply ensure all future references to it don't include var.
var element = null;
Add some error checking (clearing before you click Start causes errors, for example) and you're good to go!
http://jsfiddle.net/daCrosby/MMywX/1/
The function cc has no idea what 'element' is. The easiest way to fix this is to use jquery. When you delete the div, do something like
$('#pos').remove()
This finds the div with id 'pos' and removes it. You may need to pass the id of the div to cc if it's not just 'pos'.
Modern browsers supports remove() method on the element. You don't need to use external libraries as jQuery or long code. It's simple as :
var x = document.getElementById("myElement");
x.remove();
Working exemple here -> https://jsfiddle.net/tmj3p7t5/
I have set up a search in uiwebview with javascript that works great, but I want to be able to jump to the next found word in the search results. I have succeeded in geting the view to scroll to the first instance by using this code:
if (uiWebview_SearchResultCount == 1)
{
var desiredHeight = span.offsetTop - 140;
window.scrollTo(0,desiredHeight);
}
How can I get this searchresultcount to update to the next found result(say 2, 3, 4, 5, ect...) when user presses button in app?? Thanks in advance.
Do you mean a native button in your app such as a UIButton? In that case, you can use stringByEvaluatingJavaScriptFromString: to execute some JavaScript in your UIWebView. You could do something like this as the handler for your button:
- (void)buttonPressedAction:(id)sender {
NSString * js = #"uiWebview_SearchResultCount++;";
[yourUIWebView stringByEvaluatingJavaScriptFromString: js];
}
I was able to do basically the same thing with this javascript in the webview:
<script type="text/javascript">
var max = 100;
function goToNext() {
var hash = String(document.location.hash);
if (hash && hash.indexOf(/hl/)) {
var newh = Number(hash.replace("#hl",""));
(newh > max-1) ? newh = 0 : void(null);
document.location.hash = "#hl" + String(newh-1);
} else {
document.location.hash = "hl1";
}
}
</script>
Then sending this JavaScript call with my IBAction like this:
- (IBAction)next:(id)sender {
[animalDesciption stringByEvaluatingJavaScriptFromString:#"goToNext()"];
}
call this function with the appropriate row?
function scrollToDesiredHeight(row) {
var desiredHeight = span.offsetTop - 140;
window.scrollTo(0,row * desiredHeight);
}
Does this work for you?
Using javascript I'm trying to load images not on the current page (from an array of image links) and if they are large enough, add them to an array. I'm executing this after the current page has loaded, though a bookmarklet, or firebug console. Using FF.
The closest I've come is the below, but this does not seem to work, and I'm guessing this is because the size test is running before the images have loaded. Apparently my attempt to fix this with 'onload' does not work. How can I fix this up, or is there a better/simpler way to accomplish this task?
(function() {
//create array for the images
var imageArray = new Array();
function loadIfBig(x){
if (x.height > 299 && x.width > 299 && (x.height > 399 || x.width > 399)) {
imageArray.push(x);
//dispImage = '<img src=' + x.src + '><br>';
//document.write('<center>' + dispImage + '</center>');
}
return true;
}
//given an array of imageLinks:
for (x in imageLinks){
//create an image form link and add to array if big enough
im = document.createElement('img');
im.src = imageLinks[x];
im.onload = loadIfBig(im);
}
//view results:
for (x in imageArray){
disp_image = '<img src='+imageArray[x].src+'><br>';
document.write('<center>'+disp_image+'</center>');
}
})();
Update:
Thanks! sure you're right and I'm missing something stupid here, but I made the change you suggested, and then pulled writing the elements into loadIfBig, but it doesn't seem to be executing that function. current code below, including a couple sample input links:
(function() {
var imageArray = new Array();
var imageLinks = ['http://1.bp.blogspot.com/_mfMRTBDpgkM/SwCwu1RPphI/AAAAAAAAJpw/v9YInFBW84I/s1600/800px-San_Francisco_in_ruin_edit2.jpg','http://2.bp.blogspot.com/_mfMRTBDpgkM/SwCwulSZ_yI/AAAAAAAAJpo/NsRcJdpz4Dk/s1600/San_Francisco_PC_59.jpg']
function loadIfBig(x){
if (x.height > 299 && x.width > 299 && (x.height > 399 || x.width > 399)) {
imageArray.push(x);
dispImage = '<img src=' + x.src + '><br>';
document.write('<center>' + dispImage + '</center>');
}
return true;
}
processImages = function(){
for (x in imageLinks) {
//create an image from link and add to array if big enough
im = document.createElement('img');
im.src = imageLinks[x];
im.onload = function(){
loadIfBig(this);
}
}
}
})();
Your fix doesn't work because you're actually executing it immediately.
im.onload = loadIfBig(im) is actually running the function.
What you can do is something like:
im.onload = function() {
loadIfBig(this);
}
Another problem is the fact that you're running through the array of big images before the onload callbacks have actually executed. That needs to be stuck in a different function and called once all the onloads are done.