.js, css or html - how change object to two different colors? - javascript

I ask participants yes/no questions in an experiment and they answer by keypress (Y/N). Now, I want to display YES green and NO red.
I'm doing this with Ibex farms where you have an experiment file in .js format. In this file, one defines the "Question controller" as follows:
"Question", {
as: [["Y","Yes"],["N","No"]], //defines keys+answer displays
}
Adding html tags <font-size>, <div style> in this line did not work.
Besides that, there is a .css file in which I can change the color for both answers, but give the same color to both:
span.Question-fake-link {
color: #ff6600; //changing this to red; both Yes and No are red now
cursor: pointer;
}
The third file is a Question.js file which defines behavior and properties of the question controller beyond its appearance. It is too long to post here, I think, and I don't have authorship. But in there, the answers are defined as "left Comment" and "right Comment". So I attempted to add the 4th line at the (I hope) relevant place:
var lcd = $(document.createElement("li"))
.addClass(this.cssPrefix + "scale-comment-box")
.append(this.leftComment);
.document.getElementById("leftComment").style.color = "red"; //added this, made experiment dysfunctional
this.xl.append(lcd);
Does anyone know how to change the colours individually?
I'm sorry, I know this must look complicated, but maybe someone can give me a pointer on what to do...If you need more of the scripts, please let me know.
Many thanks.
EDIT: After trying out some of the suggestions here, I see the answers are somehow as "span.fake-link". Maybe this code snippet can help (line 1/2):
var a = $(document.createElement("span")).addClass(this.cssPrefix + "fake-link");
__Question_answers__[i] = ans;
__Question_callback__ = function (i) {
var answerTime = new Date().getTime();
var ans = __Question_answers__[i];
var correct = "NULL";
if (! (t.hasCorrect === false)) {...}
}
But how can I replace "span" or "fake-link"? I guess I have to replace both. Removing the span.fake-link properties in css-files doesn't seem to help.
EDIT: Or could this be the problem?
if ((this.presentAsScale || this.presentHorizontally) && this.leftComment) {
var lcd = $(document.createElement("li"))
.addClass(this.cssPrefix + "scale-comment-box")
.append(this.leftComment)
.appendTo(this.xl)
this.xl.append(lcd);
}
I attempted to replace "scale-comment-box" by "red" (defined as a class in css before), but that also doesn't help.

You could probably use jquerys css function:
$("<li>")
.addClass(this.cssPrefix + "scale-comment-box")
.css({color:"red"})
.append(this.leftComment)
.appendTo(this.xl);

Since you're already using Javascript, is it feasible for you to add two extra css classes?
One could be .red and the other, .green and then append those classes to the element accordingly at creation:
//CSS
.red{
color:#F00;
}
.green{
color:#0F0;
}
//javascript
//Your javascript seems to be a mix of jQuery and JS so I assume jQuery is imported. If this is incorrect, you would need to use a raw javascript solution
//Hint: Look at document.getElementsByClassName and .classname += "red"
//jQuery version:
$("li").addClass("red") //for any items that need to be red. replace red with green for the green items

Related

Can you change out an image in CSS using JavaScript

I'm currently creating an online quiz with HTML, JS, & CSS.
I have created question boxes that cycle through each question, but I am trying to have a different image displayed for each new question.
I currently have a CSS element that can place an image into the quiz box but doing that means I have the same image for every question.
I was hoping to use JS to change the image but I haven't quite got it yet.
.styledimg {
background-image: url(spider.png);
background-repeat: no-repeat;
width: 640px;
height: 360px;
}
Here I have the image contained in the CSS element
let questions = [
{
numb: 1,
question: "Question",
answer: "option",
options: [
"option",
"option",
"option",
"option"
]
},
Here is the start of the array that houses my questions
<div class="styledimg"></div>
Here is the tag associated with the CSS element
I was trying to use something like 'document.querySelector("styledimg").style.background-image = "clock.png"'
to change the image for each question but to no avail.
If anyone could point me in the right direction that would be appreciated.
Try
document.querySelector(".styledimg").style.backgroundImage = "clock.png"
You can also do this by adding a class to this element:
.styledimg {
background-image: url(spider.png);
}
.styledimg.clock {
background-image: url(clock.png);
}
document.querySelector(".styledimg").classList.add('clock');
It would be nice to have a working snippet. (HTML+CSS+JS)
Other than that, you should simply create an <img id="quizzImg" src="spider.png"> tag into the <div>.
After that, simply:
const quizzImage = document.querySelector("#quizzImg")
quizzImage.setAttribute("src", "clock.png")
You would just have to wrap that into a function, and call it whenever you change of question, pass as argument the new image file name, and you're set and it will be easy to use on your end.
const quizzImage = document.querySelector("#quizzImg")
function setQuizzImage(src) {
quizzImage.setAttribute("src", src)
}
Done, you have a function that can be used again and again to change the image by anything you want, you just have to call that function and pass the file name as an argument like:
setQuizzImage("clock.png")
All that is left is to make the condition over it to determines when you will run it, and what image you will set based on that condition.
As we have no idea of your code structure and process, I will try to guess. If you call a function to change the question, you could store the question number in a variable, and based on that number, make usage of a if statement in something like that:
function changeQuestion() {
[...]
if (currentQuestion == 1) {
setQuizzImage("question1.png")
} else if (currentQuestion == 2) {
setQuizzImage("question2.png")
} else
[...]
}
You could imagine setting it here. (of course, I had to hardcode the if as I have no idea of how your code works)

Apply style on insert into div

I'm building a search by tags input box as seen here:
http://jsfiddle.net/Newtt/7nUAf/
Forgive the terrible styling as this is just a small component of a larger application and I've just added the styles needed to show my issue.
My search box is a div that has it's text inserted using Jquery as follows:
$(document).ready(function () {
$('.search-box').click(function () {
$('.search-options').toggle();
});
$('.options').click(function () {
var d = $('.search-box').html();
console.log(d);
var c = $(this).html();
console.log(c);
if (d != '') {
$('.search-box').html(d + ', ' + c);
} else {
$('.search-box').html(c);
}
$('.search-options').hide();
});
$('#reset').click(function () {
$('.search-box').html('');
});
});
where .search-box is the input div, .options are the clickable options from the drop down box search-options.
Currently, the text of each option is inserted into the search-box div. I need this to be styled dynamically while it enters the search box.
I tried something on the lines of:
$('<span>').addClass('tag').append(
$('<span>').text(value).append(' '),
$('<a>', {
href : '#',
title : 'Removing tag',
text : 'x'
});
where the tag class is defined in the style sheet to style the element to look like a tag,
but this doesn't work at all. Can someone help me out with how to achieve styling the input text to look like a tag from, say, Evernote notebooks?
Thanks!
I adapted your fiddle. Just wrap c in a span with a class (like you were trying to do in the second part of your post) and apply styles in css. I have just made the background red, but it should be easy enough to make it look like a tag like the ones in the drop down do.
http://jsfiddle.net/7nUAf/1/
JS:
$('.options').click(function () {
var d = $('.search-box').html();
var c = $(this).html();
$('.search-box').append('<span class="tag">'+c +'</span>');
$('.search-options').hide();
});
CSS:
.tag {
background: red;
}
For what you are looking to do - there are lots of excellent plug ins already available that provide much "prettier" functionality and with much less work on your part. Some have already been suggested in the comments - I might suggest consider using "chosen". The syntax is amazingly simple. Just create a select box as follows:
<select id="test" multiple>
<option>pdf</option>
<option>document</option>
</select>
Then in your document ready function you simply need to call chosen plugin:
$(document).ready(function () {
$('#test').chosen({width: "80%"});
});
I put together an example that does this on JSFiddle here: http://jsfiddle.net/7nUAf/3/. Once you get to the point that you have it working you can easily style the elements by inspecting what elements chosen is creating. For example the "li.search-choice" selector will allow you to style the selected items.
In General - even if you don't like this particular plug in, always consider running a search for existing items that do what you are looking for. In the case that these aren't perfect you can always improve them and provide that insight back to the community as a whole. In that way, everyone learns together.
Best of luck!

How can I implement pseudo-dynamic css?

Im having trouble with managing custom colored elements on the page.
For example, we have 100 navigation squares on the page, each one has its own color, cant think of any way except of creating css classes for each type of color. Which will produce LOTS of css code.
Need some help with this,
Thanks
*added javascript & jquery tags as one of the possible ways of solving this question
Update:
Thanks for responses guys, feeling like I need to get into details.
Im having squared category navigation on my search page, colors can go from server side or can be stored in client's js.
Im getting list of categories from server (lets assume im getting color for each one too)
Then Im building all squares (they are white by default, but on :hover they change their color)
So I would go for such solution:
<ul id="squares">
<li class="greencolor"></li>
<li class="redcolor"></li>
<li class="bluecolor"></li>
</ul>
with css:
#squares li.redcolor:hover{
background:red;
}
#squares li.greencolor:hover{
background:green;
}
#squares li.bluecolor:hover{
background:blue;
}
Hopefully now you can see what I was talking about referring tons of css code for 100 elements.
And yes, I understand that I can go for such solution:
var colorsMap={'redcolor':'red','greencolor':'green'};
$('#squares li').on('hover',function(e){
$(this).css('background-color', colorsMap[$(this).attr('class')];
});
but this doesnt sound as an elegant solution to me and Im trying to find way to make it through css, not inline css changes by js
Although I recommend to use CSS to achieve it, but there's still a solution better than inline style:
var selector = '#squares li'
, css = []
, style = document.createElement( 'style' )
, colorsMap= {
'redcolor': 'red',
'greencolor': 'green',
'bluecolor': 'blue'
}
$( selector ).each( function() {
css.push( selector +
'.' +
// recommand to use data-attr to store color info
// assuming `className == 'bluecolor'`
this.className +
':hover' +
'{' +
'background:' +
colorsMap[ this.className ] +
'}'
)
})
style.textContent = css.join('')
document.head.appendChild( style )
By dynamic insert CSS into <head>, you still get the benefits from normal CSS, demo.
And, you also can generate dynamic CSS file in back-end side, it's more easier to manage colors, by a configuration form or something else.
First,my English is poor(But I'm trying my best to learn).So I can't say that I understand you clearly.But what you say let me think of the chooser.I didn't know if it is you want,but I think it's not a bad idea. Just like these:
$(":header").css("color","#FF00FF");
$("div:contains('test')").css("background","#666600");
$("div:empty").css("background","#888800");
$("div:has(span)").css("background","#008080");
etc.
Their role's I won't say it.I think it nessary for to learn, they are very useful.

Change text color based on background color?

I've a pretty minimalistic site, so I want to add details to it, like a hidden theme switching. But I don't want to tell the user that the theme can be changed, so I want to hide the text.
I've tried this:
var tausta = $(body).css("background-color");
$('.piiloteksti').css("color",tausta);
But it doesn't do anything. What would be the correct approach?
A fiddle.
if($('.piiloteksti').css("color",tausta); is a wrong statement. Thats a syntax error! There shouldn't be any if here.
Either remove if
$('.piiloteksti').css("color",tausta);
or complete the if statement.
if($('.piiloteksti').css("color",tausta)){
// some other code
}
Also $(body) does not refer to anything. Use either $('body') or $(document.body)
I tried to modify CSS, and it works.
// javascript
var tausta = $('body').css("background-color");
if($('.piiloteksti').css("color") == tausta) {
alert(tausta);
}
// css (test)
body{background-color:red;}
.piiloteksti{color:red;}
The syntax of your the if statement was off a little. Also, body must be made a String literal.
var tausta = $("body").css("background-color");
$('.piiloteksti').css("color", tausta);
Example: http://jsfiddle.net/HbAHS/8/
You can hide the element with CSS
.piiloteksti{display:none;} Fiddle
OR if you think that would interfere with your layout then,
.piiloteksti{visibility:hidden;} Fiddle
Or you can just give transparent color to your piiloteksti elements
.piiloteksti{color:transparent;} Fiddle

How do you change the background color of an <input> element with javascript

I have a <input> element that I want to change the background color on. The code I am currently using is this (but it is not working):
var allBlanksLoc = document.getElementById('text');
var allBlanks = allBlanksLoc.getElementsByTagName('input');
for(i=0; i<allBlanks.length; i++) {
var currentBlank = allBlanks[i];
var wordNum = blanks[i];
var blankWord = text[wordNum];
var usrAnswer = currentBlank.value;
if (usrAnswer != blankWord) {
currentBlank.style.backgroundColor = "red";
}
}
The third to last line being the most important
Update:
I fixed the camelCase on it but it still does not work. Any ideas of bugs there?
The full code is here: http://jsbin.com/imolo3/edit
Case is important. What you need is
document.getElementById('test').style.backgroundColor='red';
However
it would be better to use a css rule and use javascript only to add the class to the element.
CSS Rule
input.invalid {
background-color: red;
}
Javascript
element.className = 'invalid';
It should be backgroundColor - notice the capital C, JavaScript is case-sensitive.
Are you sure that this script is running at the right time? If it runs before the page is fully formed, the appropriate elements might not be present.
So not to repeat the solutions other users gave.
I personally use JQuery (and it's where any javascripter ends, overall for browser compatibility issues), and it would:
$(currentBlank).css("background-color","red");

Categories

Resources