Can't figure out why my JS doesn't work - javascript

I've been messing around with JavaScript samples and ever since I edited this one I can't figure out why it wont work. Everything looks fine to me, but here is the code (JSFiddle)
https://jsfiddle.net/en2a8c1v/1/
function click(e) {
document.body.style.backgroundColor='" + e.target.id + "';
}
document.addEventListener('DOMContentLoaded', function () {
var divs = document.querySelectorAll('div');
for (var i = 0; i < divs.length; i++) {
divs[i].addEventListener('click', click);
}
});

First, make sure that in the JS settings you have no-wrap enabled (I used no-wrap head) in the load type dropdown.
Next, you need to understand that when you call e.target.id, this is already a string variable. You are literally making the background color "e.target.id". That isn't a color.
Simply change document.body.style.backgroundColor='" + e.target.id + "';
to document.body.style.backgroundColor= e.target.id;
I'm not going to touch on the fact that this is a terrible way to go about this as I am assuming you are just playing with event handling.

Maybe someone will find this usefull. Use CSS attribute: background-color:rgb(x,y,z);
You can do it on simple way, for example:
document.getElementById("elementID").style.backgroundColor = 'rgb('+ this.red + ', ' + this.green + ', ' + this.blue + ')';
These r,g,b values can be, for example:
this.red = 0;
this.green = 255;
this.blue = 130;

Related

JavaScript if statement changing text color

This is my first post on these forums. I'm trying to create a table that calls its numbers from a VoIP test result on a program that I run in the HTML. currently, im trying to make the result table look "pretty" by if the VoIP Jitter is recorded 1 or above it will change the text color to red and vise versa to green.
function testFinished(vJit) {
voipcolor(vJit);
document.getElementById("aftert").innerHTML='<table class="tableRes" id="tableRes"><style>table {border:1px solid black; margin-left:auto; margin-right:auto;} th, td{border:1px solid black;}</style><thead><thead><tr><th colspan="2">VoIP Test</th></tr></thead><Tr><td>Jitter</td><td>' + vJit + 'ms</td></tr></table>';
}
I have also created the an if statement but for some reason, I keep getting errors for the "unexpected token if":
function voipcolor(vJit)
if (vJit < 1) {
let vJit = '<p style="color:green;">' + vJit + '</p>'
}else if (vJit >= 1) {
let vJit = '<p style="color:red;">' + vJit + '</p>'
}
}
there is more to the table but because i am asking about the colors i figured i would just refrence 2 cells instead of 10 or more.
what is causing the error with the if statement?
what is the proper way to insert the color change?
so I realize I need a return statement and tried adding that to the function also I beleave I edit the else issue that #Taplar was mentioning.
function voipcolor(vJit) {
if (vJit < 1) {
return voipcolor.style.color = "green"
}else{
return voipcolor.style.color = "red";
}
}
but nothing is happening. I believe I need to call the voipcolor(vJit) but im not sure how.
I'm not sure how all your HTML/CSS is defined, but can you make your code look something like this?
if (vJit < 1){
p.style.color = "green";}
if (rating >= 1){
p.style.color = "red";}
Playing with this might help too: https://www.w3schools.com/js/js_htmldom_css.asp
so I ended up asking my mentor/teacher/boss ... thing... person, for some help. I was not calling the function with the if statement. so what I did was called the function from the table replacing + vJit + with function voipcolor(vJit)
then in the voipcolor function instead of return voipcolor.style.color = "green" I used return '<span style="color: green">' + vJit + '</span>'
Because I am calling the function the whole function runs in order. when I use the return statement, the function stops running at the return statement. there are other ways to make this work and explaining this is more for my understanding than anything else. I do hope people will learn from this and understand the innerHTML attribute as I have.

Unable to alter the css 'background-image' with Jquery

I am trying to cycle through an array of pictures to make a photo-viewer on my webpage. The cycling method is working fine, but the transferring the message unto the css is not. I am wondering if there is any syntax issues within my javascript code or a concept that I am missing out on. I know that the cycling works because the alert I have is working.
var changeIt = ""
var backgroundPic = new Array(4);
backgroundPic[0] = '("images/displayPic1.jpg")';
backgroundPic[1] = '("images/displayPic2.jpg")';
backgroundPic[2] = '("images/displayPic3.jpg")';
backgroundPic[3] = '("images/displayPic4.jpg")';
backgroundPic[4] = '("images/displayPic5.jpg")';
var picCounter = 0;
var numberOfPics = 5;
var picTimer;
function setPic(){
alert("hi I want this pic: " + backgroundPic[picCounter]);
$('slider').css('background-image', url + "backgroundPic[picCounter]");
picCounter += 1;
if(picCounter >= numberOfPics){
picCounter = 0;
}
}
$(document).ready(function(){
$('.slider').css('background-image', backgroundPic[picCounter]);
picTimer = setInterval(setPic, 2000);
});
The issue is due to the incorrect syntax you're using when concatenating the CSS property value. Try this:
var backgroundPic = [ 'images/displayPic1.jpg', 'images/displayPic2.jpg', 'images/displayPic3.jpg', 'images/displayPic4.jpg', 'images/displayPic5.jpg' ];
var picCounter = 0;
var picTimer;
function setPic() {
// note the . in the jquery object below to indicate a class selector
$('.slider').css('background-image', 'url("' + backgroundPic[picCounter % backgroundPic.length] + '")');
picCounter++;
}
$(document).ready(function() {
picTimer = setInterval(setPic, 2000);
setPic();
});
You have to set background image like this:
$('.slider').css('background-image', "url('" + backgroundPic[picCounter] + "')");
You inverted the positioning of the quotemarks on the second line of setPic.
Try: $('slider').css('background-image', 'url' + backgroundPic[picCounter]);
On your setPic function, this line
$('slider').css('background-image', url + "backgroundPic[picCounter]");
isn't missing a dot on $('.slider')?
You'll need to include double quotes (") before and after the imageUrl like this:
$('slider').css('background-image', 'url("' + backgroundPic[picCounter] + '")');
This way, if the image has spaces it will still be set as a property.

sliding form not working properly?

1) I need "open panel" and "close panel" working but it cannot work properly
2)The code is in the below link.
3)please check the link you can understood properly
http://jsfiddle.net/vamsivelaga/2jgL44c5/
function slide_open(){
var a=document.getElementById("strip");
a.setAttribute("onClick","close_panel()");
close_panel();
}
function open_panel(){
var right_position= 0;
var slide_form=document.getElementById('contact_form');
if(parseInt(slide_form.style.right) < right_position){
slide_form.style.right=parseInt(slide_form.style.right) + 2 + "px";
setTimeout(open_panel(), 1);
}
slide_open();
}
function slide_close(){
var a=document.getElementById('strip');
a.setAttribute("onClick", "open_panel");
open_panel();
}
function close_panel(){
var right_position= -200;
var slide_form=document.getElementById('contact_form');
if(parseInt(slide_form.style.right) > right_position){
slide_form.style.right=parseInt(slide_form.style.right) - 2 + "px";
setTimeout(close_panel(), 1);
}
slide_close();
}
I'd suggest a much simpler solution. Always try to do all you CSS styling within your CSS files, and control different states by applying and removing classes on your elements. Like so:
var strip = document.getElementById('strip');
var slide_form=document.getElementById('contact_form');
strip.addEventListener('click',function(){
if (slide_form.classList.contains('open'))
slide_form.className = slide_form.className.replace(' open', '');
else
slide_form.className = slide_form.className + ' open';
});
Here's a fiddle.

Javascript loop to update image is returning broken image

I am new to javascript and am trying to create this loop to simulate some dice rolls. When I click roll none of the images are refreshed and it ends with the broken image shown. Can anyone see where my error is?
function roll(){
for(x=0;x<10;x++){
var die_num1 = Math.ceil(Math.random()*6);
for(y=0;y<20;y++){
var picturetype1 = Math.ceil(Math.random()*3);
if (picturetype1 == 1){prefix1 = "die-";}
if (picturetype1 == 2){prefix1 = "dicet-";}
if (picturetype1 == 3){prefix1 = "dices-";}
document.getElementById("dice").src='http://localhost/CodeIgniter_2.1.2/dice/' + prefix1 + die_num1 + '.gif';
}
}
}
body:
<input type ="button" value = "Roll" onclick="roll()" >
<img name="dice" id="dice" src="http://localhost/CodeIgniter_2.1.2/dice/die-1.gif" >
I used adocument.write to make sure that at least the final image existed in my folder and it does. I would expect to see the images cycling through as the loop progresses though. Again, I have no experience with javascript and have put this together based on how I thought it should look. Any help will be appreciated.enter code here
I wouldn't expect browser as an event-driven environment even to consider updating the screen before you return from you roll(). You need to get acquainted with setTimeout and handle it as a sequence of timer events.
Thanks for setting me in the right direction. I have reworked this to use setTimeout as Michael suggested and it is working great. Only needed 1/10 of a second per iteration, not much but made all the difference.
function roll2(){
var timer = setTimeout ("roll2();", 100);
i++;
if(i >= 15) clearTimeout(timer);
var die_num1 = Math.ceil(Math.random()*6);
var picturetype1 = Math.ceil(Math.random()*3);
if (picturetype1 == 1){prefix1 = "die-";}
if (picturetype1 == 2){prefix1 = "dicet-";}
if (picturetype1 == 3){prefix1 = "dices-";}
if (i <=15) {
document.getElementById("dice").src='http://localhost/CodeIgniter_2.1.2/dice/' + prefix1 + die_num1 + '.gif';
}
if (i >=15) {
document.getElementById("dice").src='http://localhost/CodeIgniter_2.1.2/dice/die-' + die_num1 + '.gif';
i=0;
}
}

Dual Twitter feeds with jquery fadeIn and setInterval

I am making a project that shows two opposite views in two divs side-by-side. I have everything set up so the Tweets show in their respective div, but I'd like to make them both fade in, one tweet at a time (both sides can fade in at once, I don't mind that).
My Tweets are coming from an array, and I'm currently using the following code to push updates to the div:
for(var i=0; i < tweets.length; i++)
{
$("#proTweetList").prepend("<li><img src='" + tweets[i].profile_image_url + "' />" +
tweets[i].text+"</li>");
}
and
for(var i=0; i < tweets.length; i++)
{
$("#antiTweetList").prepend("<li><img src='" + tweets[i].profile_image_url + "' />" +
tweets[i].text+"</li>");
}
I found a great example on Stackoverflow, which is as follows:
var x=0; // The corner counter
function fading() {
$("#corner"+(++x)).fadeIn(2000); // Fade in the current corner
if (x==4) { // Last image to be faded in?
clearInterval(); // Stop interval
}
}
$(document).ready(function(){
setInterval("fading()",1000); // Call function every second
});
but I am very new to JQuery and cannot figure out how to translate this code into getting LI items in TWO different divs to fade in.
-- Derek
I would do something like this:
for(var i=0; i < tweets.length; i++)
{
var $item = $("<li style='display:none;'><img src='" + tweets[i].profile_image_url + "' />" +
tweets[i].text+"</li>");
$("#proTweetList").prepend($item);
$item.fadeIn(2000);
}
Didn't test that piece of code though, but I think it will work. This will create the list item within a jQuery object($item), that way you can use functions like fade on it directly.
You could do this with a simple plugin. This way you can attach the behaviour to as many divs as you like. I've written a very simple one (untested sorry) that may help:
;(function ($) {
$.fn.loadtweets = function (options) {
var settings = $.extend(
{
fadeTime : 1000,
delay: 2000,
tweets : array()
},
options
);
return this.each(
function() {
var _this = $(this),
tweets = settings.tweets,
index = 0;
var loadTweet = function() {
if (tweets.length > index) {
_this.prepend("<li><img src='" + tweets[index].profile_image_url + "' />" +
tweets[index].text+"</li>").fadeIn(settings.fadeTime);
index++;
setTimeout(loadTweet, settings.delay);
}
}
loadTweet();
}
);
};
})(jQuery);
You would call this plugin by going (I assume you have an array of tweets for each div):
$('#proTweetList').loadtweets({'tweets': proTweetsArray});
$('#antiTweetList').loadtweets({'tweets': antiTweetsArray});

Categories

Resources