CSS not getting updated through jQuery - javascript

I am stuck in a silly problem. I have two divs (white coloured). Onclick them a class should be added which changes the color from white to blue. The class is getting added but the colour is not changing. (I do not need to addClass() just to change colour, but there will be more things in that class later, right now I have to execute it properly).
The divs has a class "thumbnail", onClick I want to add "border-glow".
// ImageBox component
// Author Sayantan Hore
// Created on 19.08.2014
// --------------------------------
function ImageBox(){
this.outerContainer = null;
this.imageBoxArray = [];
}
ImageBox.prototype.createOuterContainer = function(){
this.outerContainer = $("<div></div>")
this.outerContainer.addClass("outer-image-container");
$("body").append(this.outerContainer);
}
ImageBox.prototype.createImageBox = function(){
if (this.createOuterContainer === null){
this.createOuterContainer();
}
var imageBox = $("<div></div>");
imageBox.addClass("thumbnail");
var closeButton = $("<div>x</div>");
closeButton.addClass("btn-close");
//imageBox.append(closeButton);
this.imageBoxArray.push(imageBox);
return imageBox;
}
ImageBox.prototype.loadImage = function(imPath, imageBox){
var img = $("<img></img>")
img.attr("src", imPath);
imageBox.append(img);
img.load(function(){
//console.log($(this).height());
imgWidth = $(this).width();
$(this).parent().height(rowHeight);
$(this).height(rowHeight);
//console.log($(this).width());
$(this).parent().width($(this).width());
});
}
var rowHeight;
$(document).ready(function(){
rowHeight = parseFloat(($(window).height() * 90 / 100) / 5);
//console.log(rowHeight);
var imageBoxObj = new ImageBox();
imageBoxObj.createOuterContainer();
for (var i = 0; i < 2; i++){
var imageBox = imageBoxObj.createImageBox();
imageBoxObj.outerContainer.append(imageBox);
var imPath = '../images/im' + (i + 1) + '.jpg';
//imageBoxObj.loadImage(imPath, imageBox);
}
console.log(screen.availHeight);
console.log($(window).height());
console.log($(".outer-image-container").height());
$(".thumbnail").on("click", function(){
$(this).addClass("border-glow");
alert($(this).hasClass("border-glow"));
})
});
here is Fiddle:
see line numbers 57-60 in javascript part.
Can anybody help please?

.outer-image-container .thumbnail.border-glow{
background-color: #0066CC; }
This should make the trick, just replace your borderglow class with this.

the background-color in the class thumbnail is overriding the one in class `border-glow``because it gave more strong css selector. The simpler solution would be to edit the CSS like this :
.border-glow{
background-color: #0066CC !important;
}

Simply do the following
.border-glow{
background-color: #0066CC !important;
}
FIDDLE DEMO

add $(this).removeClass("thumbnail"); before
$(this).addClass("border-glow");

Related

jQuery mouseenter only works on first page load

This code presents a grid of colored cells that change color on mouseenter, leaving a trail of cells of the new color. A button reloads the grid with cells of the original color. Problem is the mouseenter color change works only after the first grid load (on page refresh) but not on subsequent loads after the Create New Grid button is clicked.
I am new to javascript and jQuery and though I've been over the class materials and read some articles on how to do various parts of this, I cannot see what is wrong.
Visit the jsfiddle here.
var gridWidth = 600;
var fillGrid = function(){
$('.grid').empty();
var cellsPer = prompt('How many cells would you like in a side?');
console.log('cellsPer = ' + cellsPer);
var cellWidth = (gridWidth / cellsPer) - 1;
console.log('cellSize = ' + cellWidth);
var cell = "<div class='cell'></div>";
for (var i = 0; i < cellsPer**2; i++) {
$('.grid').append(cell);
};
$('.cell').css({
'background':'blue','height': cellWidth+'px', 'width': cellWidth+'px',
'float':'left','margin': '0 1px 1px 0'
});
};
$(document).ready(function() {
fillGrid();
$('.grid').css({'width': gridWidth+'px'});
$('button').click(function(){
fillGrid();
});
$('.cell').mouseenter(function() {
$(this).css('background','pink');
});
});
You where adding the mouseenter event listener only once on $(document).ready.
When fillGrid() gets called, a new set of '.cell' elements not bound to the mouseenter event get added to DOM.
You must tell them to behave the same again.
See the following snipped:
var gridWidth = 600;
var fillGrid = function(){
$('.grid').empty();
var cellsPer = prompt('How many cells would you like in a side?');
console.log('cellsPer = ' + cellsPer);
var cellWidth = (gridWidth / cellsPer) - 1;
console.log('cellSize = ' + cellWidth);
var cell = "<div class='cell'></div>";
for (var i = 0; i < cellsPer**2; i++) {
$('.grid').append(cell);
};
$('.cell').css({
'background':'blue','height': cellWidth+'px', 'width': cellWidth+'px',
'float':'left','margin': '0 1px 1px 0'
});
$('.cell').mouseenter(function() {
$(this).css('background','pink');
});
};
$(document).ready(function() {
fillGrid();
$('.grid').css({'width': gridWidth+'px'});
$('button').click(function(){
fillGrid();
});
});
button{
display:block;
margin:5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Create New Grid</button>
<div class="grid"></div>
Move it outside $(document).ready function and add the mouse enter functionality as
' $(document).on('mouseenter','.cell',function() {
$(this).css('background','pink');
});'
Two issues I notice with this code
1) cellsPer ** 2 is not valid. Use Math.pow or cellsPer * cellsPer
2) You are only setting up the mouse enter listener on document.ready. Calling empty on your grid will remove all child elements - attached event listeners and all. This means you will need to re-add the event listeners every time you re-initialize the grid.
Here is an updated snippet with minimal changes to get your code working:
var gridWidth = 600;
var fillGrid = function(){
$('.grid').empty();
var cellsPer = prompt('How many cells would you like in a side?');
console.log('cellsPer = ' + cellsPer);
var cellWidth = (gridWidth / cellsPer) - 1;
console.log('cellSize = ' + cellWidth);
var cell = "<div class='cell'></div>";
for (var i = 0; i < cellsPer * cellsPer; i++) {
$('.grid').append(cell);
};
$('.cell').css({
'background':'blue','height': cellWidth+'px', 'width': cellWidth+'px',
'float':'left','margin': '0 1px 1px 0'
});
};
$(document).ready(function() {
fillGrid();
$('.grid').css({'width': gridWidth+'px'});
$('button').click(function(){
fillGrid();
$('.cell').mouseenter(function() {
$(this).css('background','pink');
});
});
$('.cell').mouseenter(function() {
$(this).css('background','pink');
});
});
button{
display:block;
margin:5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Create New Grid</button>
<div class="grid"></div>
Since you're doing this for a class I'm not going to refactor the code but, one other suggestion I would make is adding the event listener in the fillGrid function, that way you neatly encapsulate everything that has to do with the grid in one place.

jQuery detect background color of a fixed element

I have a white menu button that has a fixed position. I have a section on my website that has a white background color. My goals is that when the menu button scrolls over the white section it turns black instead of white.
I just have no idea how I can detect the background color of my fixed element? Is this even possible?
here's what my jQuery looks like:
$color = how to detect bg color?;
if ($color == "#fff"){
$("nav-icon2").css("color", "#000");
}else{
$("nav-icon2").css("color", "#fff");
}
Here's a working fiddle based on this solution :
How to get the background color code of an element?
See this fiddle
var color = '';
var x = $(".nav-icon2").css('backgroundColor');
hexc(x);
alert(color);
function hexc(colorval) {
var parts = colorval.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
delete(parts[0]);
for (var i = 1; i <= 3; ++i) {
parts[i] = parseInt(parts[i]).toString(16);
if (parts[i].length == 1) parts[i] = '0' + parts[i];
}
color = '#' + parts.join('');
}
EDIT :
If I understand correctly your issue, you wants this :
See this updated fiddle
$(window).scroll(function(){
if($(window).scrollTop() > 350){
$("h2").css('color','#f00');
}else{
$("h2").css('color','#fff');
}
});
Simple!
var $color = $('nav-icon2').css('background-color');
You can do this with:
$color = $( "your-element" ).css( "backgroundColor" );

Loop 3 images from my Div background-image Property

I have a code to loop images but based on an Img source, but how to improve it to make it work for the "background-image" property of a div?
HTML
<div id="section2"></div>
CSS
#section2 {
background-image: 'url(..images/banner1.jpg');
}
JAVASCRIPT
<script type = "text/javascript">
(function() {
var i = 1;
var pics = [ "images/banner1.jpg", "images/banner2.jpg", "images/banner3.jpg" ];
var el = document.getElementById('section2');
function toggle() {
el.src = pics[i];
i = (i + 1) % pics.length;
}
setInterval(toggle, 3000);
})();
</script>
Thanks in Advance :)
One way would be to use CSS classes instead of sources.
JS:
<script type = "text/javascript">
(function() {
var i = 1;
var classes = [ "bgd-1", "bgd-2", "bgd-3" ]; // adjusted
var el = document.getElementById('section2');
function toggle() {
el.className = classes[i]; // adjusted
i = (i + 1) % classes.length; // adjusted
}
setInterval(toggle, 3000);
})();
</script>
CSS:
#section2.bgd-1 {
background-image: url('..images/banner1.jpg');
}
#section2.bgd-2 {
background-image: url('..images/banner2.jpg');
}
#section2.bgd-3 {
background-image: url('..images/banner3.jpg');
}
Note:
Use el.className += ' ' + classes[i]; to append a class name instead of replacing all element classes.

Fading out in Javascript

Hey I'm new to javascript and I'm working on a small chat program right now.
I've got all the chatlogs (global& private and stuff..) but i want to add a button which can make (most of) the elements of these little 'clients' fade out and in, so that you dont have to see ALL of them at one time, just the ones you want.
The (relevant) code with the example element mess1:
h=0;
newroom = function (roomname) {
//create new container
var div = document.createElement('div');
div.className = 'container';
//new text input
var mess = document.createElement('input');
mess.type = 'text';
mess.id = 'mess1' + i;
div.appendChild(mess);
//minimizer button
var min = document.createElement('input');
min.type = 'button';
min.value = 'Minimize chat';
min.id = 'min' + i;
div.appendChild(min);
document.body.appendChild(div);
document.getElementById("min" + h).addEventListener("click", function (){
//this is where the magic happens
}
h++;
};
I've tried document.getElementById("mess1" + h).style.visibility = 'hidden';, but that just makes the element disappear, leaving a big ugly blank space behind.
I thought document.getElementById("mess1" + h).fadeOut('slow'); would fix that, but it just doesn't do anything...
Thanks in advance for your answers
function fadeout(element) {
var op = 1; // initial opacity
var timer = setInterval(function () {
if (op <= 0.1){
clearInterval(timer);
element.style.display = 'none';
}
element.style.opacity = op;
element.style.filter = 'alpha(opacity=' + op * 100 + ")";
op -= op * 0.1;
}, 50);
}
first of all I will recommend to use jQuery, it will make your life much more easy. In jQuery, you can fade the element and then remove it like this
$("#mess1" + h).fadeOut('slow',function(){
$("#mess1" + h).remove();
});
It will first fade the element and will then remove it from node if required
You can use
document.getElementById("mess1" + h).style.display= 'none';
it will hide element without empty space. But if you whant to hide element with animation you can use eq. this jquery:
$("#mess1" + h).hide('slow')
or eq. 'fast' - as parameter

Change background color with local.Storage (value)

I want to change the background-color of an div:
Arrow Box
For this i have to divs wich you can click. The triggerd function saves the local storage value of the "farbe" key.
<div class="radior" style="background-color:#8066CC;" onClick='localStorage.setItem("farbe","#8066CC");hey()'></div>
So after that, the value of the key "farbe" is asked. Besides this is makes an case ... I think you better read my code, because think i need some englisch lessons sorry!
function hey(){
switch (localStorage.getItem("farbe")){
case "#121212":
var h = "black"
case "#1bc38e":
var h = "turk"
case "#C3594B":
var h = "red"
case "#8066CC":
var h = "lila"
}
document.getElementsByClassName("arrow_box")[0].style.backgroundColor=""+h+""; ;
}
SOmehow it doesnt function!
Or you watch an example of my problem at fiddle http://jsfiddle.net/PpsLH/4/ ! Greetings from Germany!
Change your function to:
hey = function(){
switch (localStorage.getItem("farbe")){
case "#121212":
var h = "black";
break ;
case "#1bc38e":
var h = "turk";
break ;
case "#C3594B":
var h = "red";
break ;
case "#8066CC":
var h = "lila";
break ;
}
document.getElementsByClassName("arrow_box")[0].style.backgroundColor=h;
}
By the way, lila is not a valid HTML color, so it will not work.
You should remove any inline event handlers from your code. Also the whole switch section and changing to named CSS colors seem redundant. Check out this bit of code written in jQuery
var box = $('div.arrow_box');
$('body').on('click','div.radior',function(e){
var color = $(e.target).css('backgroundColor');
localStorage.setItem('farbe',color);
box.css('backgroundColor',color);
});
and a working fiddle http://jsfiddle.net/chrisdanek/BaJvC/5/
try this
<div class="arrow_box"><a>Arrow Box</a></div>
<div class="radior" style="background-color:#C3594B;" onClick="localStorage.setItem('farbe','#C3594B');window.hey()"></div>
<br>
<div class="radior" style="background-color:#8066CC;" onclick='localStorage.setItem("farbe","#8066CC");window.hey()'></div>
and for javascript
window.hey = function ()
{
var h="";
if (localStorage.getItem("farbe")=="#121212")
{
var h = "black";
} else
if (localStorage.getItem("farbe")=="#1bc38e")
{
var h = "turk";
} else
if (localStorage.getItem("farbe")=="#C3594B")
{
var h = "red";
} else
if (localStorage.getItem("farbe")=="#8066CC")
{
var h = "lila";
}
document.getElementsByClassName("arrow_box")[0].style.backgroundColor=h+"";
}

Categories