I have a script that runs when a specific element is clicked on. The script changes the background color of a div. When the user clicks on the div the background color must change to #4aa3c3, but when the user clicks on the div again, it must change back to a #fafafa. The if statement works, but for some reason, once the color is changed to #4aa3c3, it won't change back to normal. It seems like my else statement isn't working. Am I doing something wrong?
function Active() {
if (document.getElementById("test").style.backgroundColor !== "#4aa3c3"){
document.getElementById("test").style.backgroundColor = "#4aa3c3";
} else {
document.getElementById("test").style.backgroundColor = "#fafafa";
}
}
When you try some basic debugging, like
console.log(document.getElementById('test').style.backgroundColor);
Do you see the problem? Chances are, you're getting something like:
"rgb(74, 163, 195)"
So that's why the if isn't working as you'd like. But that's not your biggest issue.
The real problem is that you are using Presentation (CSS) to define Behaviour (JS). On top of that, you're using Behaviour to define Presentation.
Instead, you should do something like this:
document.getElementById('test').classList.toggle('toggled');
And use CSS to define a style like:
#test {background-color: #fafafa}
#test.toggled {background-color: #4aa3c3}
Would agree with the answer above - however to add another dimension - if you ever did need to change the returned RBG values to hex you could try something like this which would allow the code to work as stated in the original question.
<script>
function hex(x) {
return ("0"+x.toString(16)).slice(-2);
}
function rgb2hex(rgb) {
rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}
function CheckIfColorIsCorrect()
{
var hex = rgb2hex(document.getElementById("test").style.backgroundColor);
if (hex != "#4aa3c3"){
document.getElementById("topbar").style.backgroundColor = "#4aa3c3";
} else {
document.getElementById("test").style.backgroundColor = "#fafafa";
}
}
</script>
Related
I am having problems with a javascript function. I want to replace an icon by changing the class.
On my page, I have the following element:
<i class="wait icon" alt="{webui_botstatenotavailable}" title="{webui_botstatenotavailable}" id="{botname}"></i>
The following javascript should change the class, but it does not work:
function incomingBotStatusList(http_request, statusOff, statusOn)
{
if (http_request.readyState == 4)
{
if (http_request.status == 200)
{
if (http_request.responseText.length < 7)
{
// Error
}
else
{
var botStatusList = JSON.parse(http_request.responseText);
for (var key in botStatusList)
{
if (botStatusList.hasOwnProperty(key))
{
var botStatusImage = document.getElementById(key);
if (botStatusImage != null)
{
if (botStatusList[key] == 0)
{
botStatusImage.class.innerHTML = "images/bullet_red.png";
botStatusImage.title = statusOff;
botStatusImage.alt = statusOff;
}
else if (botStatusList[key] == 1)
{
botStatusImage.class.innerHTML = "<i class=\"checkmark green icon\">";
botStatusImage.alt = statusOn;
botStatusImage.title = statusOn;
}
}
}
}
}
}
}
}
Did someone from you know how it will work?
Thanks for your help!
Best Regards
Pierre
I see a couple of problems with your code. First, the <i> element is used to apply italic formatting to text. It is not the HTML code for an icon or an image.
Secondly, you write botStatusImage.class.innerHTML, but the Element.class does not exist, and Element.className is a string. It does not have an innerHTML attribute. So, you could write botStatusImage.className = "new_class_name"; and this would be more correct.
You should then change the image source by calling botStatusImage.setAttribute('src', new_url), where you have set new_url to the new image location.
Check out the javascript reference for the Element class that is returned from document.getElementById: check this link
My recommendation, start simple, then make it complex.
First, try to get the icon to change without the AJAX request. Try writing a function like this:
function changeIcon( imageId, newUrl ){
var element = document.getElementById( imageId );
element.setAttribute( "src", newUrl );
}
Then test this function in the console by passing calling it with the URL's manually.
Once that works, don't change it! Next add the AJAX call, and when you have the Icon url from your server response, all you do is call the function that you already wrote and tested. That way you separate the AJAX code from the image update code and you can test them separately.
The key is smaller functions. Build the easy stuff first, and then call those easy functions from the harder functions. Once you know the easy function works well, it becomes much easier to find problems in the harder functions.
I'm still developing a genius forum for my website. I want to add some fancy javascript effects. I don't want to use jQuery for now.
My problem is the following: I have an element which appears by checking if the value of the function is true or false. With those check my article shows or hides.
My question is: Is it possible to use transitions so that my block drops down like the way transitions do?
The first js function describes the check and the next function hides or show my article when the values are not empty.
function CheckEmptyValues() {
var inputFields = document.getElementsByTagName('input');
var textFields = document.getElementsByTagName('textarea');
var postData = [inputFields, textFields];
for(var i=0; i<postData.length; i++) {
for(var j=0; j<postData[i].length; j++) {
if(postData[i][j].value !== '') {
return false;
}
}
}
return true;
}
function showPreview() {
if (CheckEmptyValues() === false) {
this.prevPost.style.display = "block";
}
else {
this.prevPost.style.display = "none";
}
}
When my emptyvalues are false the article appears and if not, it disappears. But when this happens you see only show or hide, no further effect or something.
I want to make this something like this effect: http://www.w3schools.com/css/tryit.asp?filename=trycss3_transition1
The height value should start with 0 and end with 150 height or something like that.
Does anyone have a solution how to make this look cool?
Thanks in advance.
No, you can't, display is defined as non animatable.
If you want workarounds, see CSS3 Animation and Display None.
No, display doesn't come in transition-property. But, you can try opacity and for the display:block , put it in your div:hover or only div css.
You could use opacity, and set it to 0 or 1:
this.prevPost.style.display = "block";
this.prevPost.style.opacity = 1;
i'm with a little problem. I was building a form in HTML with javascript, but in the inputs, i've used a background-image and a padding in left to make it look better, here its all ok, the problem comes next. I've created this function here:
function verificar_email(email) {
var valor = email.value;
if (valor.length != 0){
if (valor.indexOf('#') >= 1) {
if (valor.indexOf('.') > (valor.indexOf('#') + 1)) {
if (valor.length > (valor.lastIndexOf('.') + 1)) {
email.style.background = "#1abc9c";
email.style.color = "#fefefe";
return true;
}
}
}
}
email.style.background = "#ff0000";
email.style.color = "#fefefe";
return false;
}
When the email input is blank or typed wrong, it's filling my bgimage with bgcolor and making the image dissapear. How can i change my original image to other image i've created without filling with color?
Sorry for my bad english, below i will explain what i'm talking about with some images.
http://imgur.com/a/hkigg - the first image is the error, the second is what it looks like and the final image is what i wanna do.
you can simply set the background color to "transparent" which should stop your background image disappearing
I am working on homework that involves working with javascript. Part of my homework assignment is to use the event handlers onmouseout and onmouseouver. What is supposed to happen when the user hovers over a specific div element, the font size grows by 25%, and when the user mouses out of the div element, the font size goes back to normal. My question is, is it possible to incorporate both an onmouseover function and an onmouseout function into one function? Somehow that is what my teacher wants us to do. I have this started so far.
function FontSize(x)
{
x.style.fonstSize = large;
}
I'm also thinking this isnt the correct code to make the font 25% larger, but I'm not sure how to really incorporate an onmouseout in this function.
As a teacher myself, I am 99% sure that by "one function" the instructor means one general-purpose function to change the font size, not one function which uses conditional statements to work backwards and figure out whether it should be doing onmouseout or onmouseover.
Your script should contain:
function resize(elem, percent) { elem.style.fontSize = percent; }
Your HTML should contain:
<div onmouseover="resize(this, '125%')" onmouseout="resize(this, '100%')"
Text within div..
</div>
Note: Situations such as here, are exactly why JavaScript has the keyword "this"--to save us from needing to use complicated document.getElementById() statements.
You can use "%" property for controlling font-size as described here with the following code.
document.getElementById("div1").onmouseover = function() {
document.getElementById("div1").style.fontSize = "125%"
};
document.getElementById("div1").onmouseout = function() {
document.getElementById("div1").style.fontSize = "100%";
};
Here is the working jsfiddle : http://jsfiddle.net/LxhdU/
Yes you can. Call the same function on both events, and pass a parameter to indicate whether the fontsize should increase or decrease.
ChangeFontSize = function(element, shouldIncreaseFontsize)
{
var small=14;
var large = small * 1.25;
if(shouldIncreaseFontsize) {
element.style.fontSize = large + "px";
}
else {
element.style.fontSize = small + "px";
}
}
http://jsfiddle.net/TMHbW/1/
I'd do something simple like the following. The large and small values can be whatever you need them to be for the font size to work or they can be variables you've defined in prior code.
Demo: http://jsfiddle.net/lucuma/EAbYn/
function doHover(e) {
if (e.type=='mouseover') {
this.style.fontSize = "large";
} else {
this.style.fontSize = "small";
}
}
var el = document.getElementById('myelement')
el.onmouseout =doHover;
el.onmouseover=doHover;
It is possible you do not need to call both the events on the element explicitly instead extension you create will do that.Extend the Element's prototype. Jquery also does similar to this.
Ref Prototype
See Fiddle:- http://jsfiddle.net/4fs7V/
Element.prototype.hover= function( fnOver, fnOut ) {
this.onmouseover=fnOver;
this.onmouseout=fnOut || fnOver;
return this;
};
document.getElementById('test').hover(function(){
//do your mouseover stuff
},
function(){
//do your mouseout stuff
});
Update
Same can be achieved with just one function too:-
Hover me
.largeFont {
font-size:125%;
}
Element.prototype.hover = function (fnOver, fnOut) {
this.onmouseover = fnOver;
this.onmouseout = fnOut || fnOver;
return this;
};
document.getElementById('test').hover(changeMe);
function changeMe()
{
if(this.hasAttribute('class'))
{
this.removeAttribute('class');
}
else
{
this.setAttribute('class', 'largeFont');
}
}
I am using mootools1.2 as my js framework.
I have one problem regarding the highlight my some html element when page gets load.
I need to highlight my error message if any on page when page loads.
For example.
When page load then error div have #FFFFFF as bg color.
For highlight it will use #FC0000 as a bg color and then after it will get back to #FFFFFF bg color.
Any one can please suggest how can i do this..
Thanks in advance.
Avinash
MooTools way:
window.addEvents({
domready: function(){
var errorMsg = $$('.errorMessageEl');
errorMsg.highlight('#FC0000');
}
});
Here's an example: http://mootools.net/shell/s7mRh/
Repeating the highlight
Repeating the highlight a number of times is a bit more complicated– you'd probably want to create a mixin like this:
Array.implement({
blink: function(color, repeats){
this.set('tween', {
link: 'chain'
});
var i = 0;
while (i <= repeats-1){
this.highlight(color);
i++;
}
return this;
}
});
var errorMsg = $$('.errorMessageEl');
errorMsg.blink('#f00', 3);
Example: http://mootools.net/shell/8M9xx/1/
I don't remember exact mootools syntax, but the idea is something like that:
window.addEvent("onload",function()
{
$('divName').style.backgroundColor='#FC0000';
setTimeout($('divName').style.backgroundColor='#FFFFFF',5000) // will wait 5 seconds before returning to orig. color
}
);
If you want it to blink, you can write a function like this:
function blinkit(){
var intrvl=0;
for(nTimes=0;nTimes<3;nTimes++){
intrvl += 1000;
setTimeout("$('divName').bgColor='#0000FF';",intrvl);
intrvl += 1000;
setTimeout("$('divName').bgColor='#FFFFFF';",intrvl);
}
}
source:
http://w3schools.invisionzone.com/index.php?showtopic=21893