Keep gradient the same when changing background image with javascript - javascript

I have a background image that I want to change every 10 seconds. However, I have a gradient on top of that image, that I dont want to change when i change the image. This is the original css:
#carBanner
{
background: linear-gradient(to bottom, rgba(0,0,0,0) 0%,rgba(0,0,0,0) 50%,rgba(230, 230, 230, 1) 100%), url('TS12-COVER.jpg');
}
Then I have javascript that has a function that is called every 10 seconds, the function looks like this:
function changeImage()
{
document.getElementById('carBanner').style.background = "url('haegri.png')";
}
When i do this, the gradient no longer appears on top of the picture.. I have also tried this:
function changeImage()
{
document.getElementById('carBanner').style.background = "linear-gradient(to bottom, rgba(0,0,0,0) 0%,rgba(0,0,0,0) 50%,rgba(230, 230, 230, 1) 100%), url('haegri.png');"
}
But then the image wont change.
Can anyone please tell me how i can change the background image and still keep the gradient? Thanks in advance!

Use CSS classes to control this behavior, you can add or remove class from your element in javascript. You CSS class can have your settings of background and gradient.

Using style.background will affect all properties of background. However if you specifically want to target backgroundImage please use below mentioned code.
function changeImage()
{
document.getElementById('carBanner').style.backgroundImage = "url('haegri.png')";
}
Update:
Since this method does not seem to work, I am posting this fiddle on lines as mentioned by kush. This method seems to work as long as you just want to swap between 2 images.
It basically uses 2 classes with two different background images. On click instead of changing just image, previous class gets removed and new class is applied.
http://jsfiddle.net/gtej2/
I will still looking for more elegant solution and will update fiddle soon.

For the image use:
background-image
Or in your code:
.style.backgroundImage ...

What about using an overlay? You place a div on which you are setting the image and another div over it on which you set your gradient.
Therefore you would have to set correctly your overlay, but with JS it's quite easy:
$(document).ready(function () {
// Set the overlay over the image slider
var left = $("#test").offset().left;
var top = $("#test").offset().top;
$("#overlay").css('left', left + 'px');
$("#overlay").css('top', top + 'px');
// Change your image
setInterval(changeImage,1000);
});
This would look like this: http://jsfiddle.net/QtBlueWaffle/Tj7j5/1/

Related

Bootstrap Studio - The style property of my `<div>` element is not changing during my JS function

I am using Bootstrap (in Bootstrap Studio) and plain JavaScript. I have colored the background of my <div> element by setting the CSS color to the default color. Now, I am trying to change that CSS color by setting a new value when a new tab is selected.
The goal is to change the background color of tabs and their corresponding content. For example, tab 1 will have a blue background, and tab 2 will have an orange background; the background color will change as you switch between them. I have set the base color by styling the parent div background. (The reason I did not color the tab-content and active tab specifically is that the colored area was not big enough).
Below is the JS function I currently have.
window.addEventListener('load', startup);
async function startup(){
// other functions
await toggleColor();
}
async function toggleColor(){
var menuItm = document.getElementsByName('tabGroup').forEach(item =>{
item.addEventListener('click', event=>{
var bg= document.getElementById('tabDiv');
var bgColor = bg.style.background;
console.log("Old Color: "+bgColor);
bgColor = 'linear-gradient(to bottom right, #ec7429, #843f1d)';
console.log("New Color: "+bgColor);
})
});
}
Bellow is the CSS styling on the parent <div id= ‘tabDiv’> , and for the active tab.
#tabDiv {
background: linear-gradient(to bottom right, #8c3a83, #682b61);
}
#tabList .nav-link.active {
color: #E7E8E9;
background: linear-gradient(to bottom right, #8c3a83, #682b61);
}
Below is the general structure of my HTML.
<div id='tabDiv'>
<ul id='tabList' class='nav nav-tabs flex-column' role='tablist'>
<li id='tabID' class='nav-item' role='presentation' name='’tabGroup'>
<a class='nav-link' role='tab' datta-toggle='tab' href='#tab-1'> TabText </a>
</li>
</ul>
<div class='tab-content'>
<div id='tab-1' class='tab-pane' role='tabpanel'>
<p> Tab Content <p>
</div>
</div>
</div>
When I run the code as it is this is what the console prints out:
Old Color:
New Color: linear-gradient(to bottom right, #ec7429, #843f1d)
Old Color:
New Color: linear-gradient(to bottom right, #ec7429, #843f1d)
So, I moved the initial CSS styling to the HTML div to look like <div id=’tabDiv’ style=”background: linear-gradient(144deg, #8c3a83, #682b61);”>. I’m using Bootstrap Studio (required by my work place), which gave me that new inline style format.
When running the code with styling in the HTML instead of the CSS files I get this:
Old Color: linear-gradient(144deg, rgb(140, 58, 131), rgb(104, 43, 97))
New Color: linear-gradient(to bottom right, #ec7429, #843f1d)
Old Color: linear-gradient(144deg, rgb(140, 58, 131), rgb(104, 43, 97))
New Color: linear-gradient(to bottom right, #ec7429, #843f1d)
I have also tried changing the formatting and color type (hex or RGB) of the HTML style declaration, and in the JS function where I set the new color. But the same basic issue of, the Old Color does not actually update/change during my JS function. I have also tried adding the !important to my new color in JS.
I’ve read that this may be an issue with what is being rendered first. As I am new to Bootstrap Studio I have tagged this here. I know that you can change the order of the same file types but is there a way to change the order of CSS vs JS? However, I’m not sure if this is it because in another function I am successfully updating the style.display from ‘none’ to ‘blocked’.
StackOverflow has offered questions similarly worded to my title. Some of them involved properly retrieving the element, and wrapping the function in a window.onload. Both of which I think have working. There is a window.addEventListener('load', function); call at the top of my JS files, and other functions called from that work properly. I have also console logged to check that tabs I am event listening for are being selected successfully and correctly, and the same for the <div id=’tabDib’> I want to change the property of. I have also tried having no default color and changing/adding the new colors in my JS function.
Does the issue lie somewhere in code or logic? Any advice would be appreciated. I know this was long, thank you for reading.
tl;dr Trying to change the styling of an HTML element using a js function but the color is not changing. This sounds like a basic issue but I haven’t found anything that has works.
First of all, if you want to set attribute (in your case the background color as inline style) you can use setAttribute method.
Secondly, the reason that you got empty value when you console loged Old color is that bg.style.background is looking for inline style attribute. If you want to use css external file you should use in your script getComputedStyle method.
SO:
item.addEventListener('click', event=> {
var bg = document.getElementById('tabDiv');
var bgColor = bg.style.background; // this will work if you use inline-style
var bgColor2 = bg.getPropertyValue('background'); // this will work if you use stylesheet
console.log("Inline Color: "+bgColor + "Stylesheet Color: "+bgColor2);
bgColor = 'linear-gradient(to bottom right, #ec7429, #843f1d)'; // this doesn't set any property to the element, it just assign a value to a variable.
bg.setAttribute('style', 'background:' + bgColor); // this will set inline style to the element with the color in the variable you declared above.
console.log("New Color: "+bgColor);
})
Thank you #a-meshu for your help! Bellow is the working version of my JS function.
async function toggleColor(){
var menuItm = document.getElementsByName('tabLeft').forEach(item =>{
item.addEventListener('click', event=>{
var bg = document.getElementById('tabDiv');
var bgColor = window.getComputedStyle(bg);
bg.setAttribute('style', 'background: linear-gradient(to bottom right, #ec7429, #843f1d)');
console.log("New Color: "+ bgColor);
})
});
}

Javascript style.background not allowing me to adjust size of image

I want the background image of the red section to change when the user hovers over the blue section.
I have got this to work fine with the following code
<script>
document.getElementById('scrolling-background-column-left').onmouseover = function()
{
document.getElementById('scrolling-background-section').style.background = "url('https://media.cntraveler.com/photos/5698051378d099fc122487e3/master/w_820,c_limit/Sunset-Beach-Oahu-cr-getty.jpg') no-repeat center";
};
document.getElementById('scrolling-background-column-left').onmouseout = function()
{
document.getElementById('scrolling-background-section').style.background = "";
};
</script>
However is the result when i hover over the blue section. Is there a way to make the image span across the entire section/whole width of the page? I have tried adding cover to the code however this doesn't seem to work, if i try changing the size of the image through the code it breaks everything.
cover should work in your case. When you use the background shorthand property, you need to have a / separating the position and size values:
document.getElementById('scrolling-background-section').style.background = "url('media.cntraveler.com/photos/5698051378d099fc122487e3/master/…) no-repeat center / cover";

JQuery - change multiple background images

I have a CSS code that creates a frame using 8 images:
background-image: url(images/blue/tl.png), url(images/blue/tr.png), url(images/blue/bl.png), url(images/blue/br.png), url(images/blue/t.png),url(images/blue/b.png),url(images/blue/l.png),url(images/blue/r.png);
background-position: top left, right top, bottom left, bottom right, top, bottom, left,right;
background-repeat: no-repeat,no-repeat,no-repeat,no-repeat,repeat-x,repeat-x,repeat-y,repeat-y;
My goal is to make a JQuery program, that can change the sources to different images. I have a problem defining the change in JQuery for multiple background images. I always end up with only one image changing.
JQuery code:
$(document).ready(function() {
$("#red").on("click", function(){
$("#outer-frame").css({'background-image': "url(images/red/tl.png)", 'background-image': "url(images/red/tr.png)"});
$("#outer-frame").css({'background-position': "top left", 'background-image': "top right"});
});
I would really appreciate if somebody who knows how to do this would help me.
Thank you for advice.
To set multiple background images with javascript, you set the style only once, but with the string of multiple backgrounds as the value, otherwise each resetting of the style overwrites the previous etc.
$("#outer-frame").css({
'background-position' : 'top left',
'background-image' : 'url(images/red/tl.png), url(images/red/tr.png)'
});

Image positioned below to be visible on mouse hover

There are two images placed one below the other, what i want to do is when you hover a mouse over the top image only the portion of the image below should be visible not the entire image to be replaced.Is this possible using jquery ?.
I am stuck on where to start. I tried changing the div background on hover but i couldn't get anywhere near what i need.Thanks.
html
<div style="background-image: url("image1.jpg")></div>
<div style="background-image: url("image2.jpg")></div>
Try this?
$(document).ready(function() {
var $hover = $("#hover");
var $foreground = $("#foreground");
$hover.hide();
$foreground.mousemove(function(event) {
var top = event.pageY - $hover.height() / 2;
var left = event.pageX - $hover.width() / 2;
$hover.css("top", top);
$hover.css("left", left);
});
$foreground.mouseover(function() {
$hover.show();
});
$foreground.mouseleave(function() {
$hover.hide();
});
});
http://jsfiddle.net/WV8jX/685/
EDIT: Updated to hide before mouse entering
http://jsfiddle.net/WV8jX/686/
EDIT:
It doesn't really solve your problem tho if you need the background to be shown as according to your description.
Since you have tagged jQuery, use the jQuery .hover().
Example:
$("selector").hover(
function() {
show your hidden image functionality here
}
);
https://api.jquery.com/hover/
I think there is no need of using Javascript/Jquery. CSS can do the job as below
HTML
<div class="bgdemo"></div>
CSS
.bgdemo{
background-image: url("image1.jpg");
}
.bgdemo:hover{
background-image: url("image2.jpg");
}
and there is a typo in your HTML, style tag is not ending properly.
edit
Check this jsfiddle, Position the background according to your requirement.
edit
Here I found good article seems bit complicated but worth reading..

JavaScript How to make an image to change color onmouseover?

I have a button and an image and want them to change color onmouseover.
The button changes color fine:
<script>
function secondColor(x) {
x.style.color="#000000";
}
function firstColor(x) {
x.style.color="#ffaacc";
}
</script>
<input onmouseover="secondColor(this)" onmouseout="firstColor(this)" type="submit"><br>
How can I do the same thing with the image? Is there any way:
<img src="..." ......
Or do I have to have a second image to replace the first one onmouseover and this is the only way?
If you don't care that much about supporting older browsers, you could use the new CSS3 filter brightness. In chrome, you could write something like this:
var image = document.getElementById('img');
image.addEventListener('mouseover', function() {
image.setAttribute('style','-webkit-filter: brightness(1.5)');
}, false);
image.addEventListener('mouseout', function() {
image.setAttribute('style','-webkit-filter: brightness(1.0)');
}, false);
I don't recommend this approach, though. Using another picture while hovering would be a better solution.
I know that this is old, but you don't need two images. Checkout my example using one image.
You can simply change the position of the background image.
<div class="changeColor"> </div>
JavaScript
var dvChange = document.getElementsByClassName('changeColor');
dvChange[0].onmouseover = function(){
this.style.backgroundPosition = '-400px 0px';
}
dvChange[0].onmouseout = function(){
this.style.backgroundPosition = '0px 0px';
}
CSS
.changeColor{
background-image:url('http://www.upsequence.com/images/multibg.png');
width:400px;
height:400px;
background-position: 0px 0px;
}
.changeColor:hover{
background-image:url('http://www.upsequence.com/images/multibg.png');
width:400px;
height:400px;
background-position: -400px 0px;
}
You can also try changing the opacity of the images onmouseover and onmouseout.
I don't have an example for that, but its super easy to find and I am sure it has be answered already on stack exchange somewhere.
In the JSFiddle below there is Javascript and non-Javascript examples.
http://jsfiddle.net/hallmanbilly/gtf2s8ts/
Enjoy!!
I think you have to use a second image. I recently cam across the following article describing how to do image crossfading on hover using css. Crossfading Image Hover Effect
You can change image SRC on mouse over, you can load two images and use fade effects to "change" them. But better, you can use image as DIV background, make sprite and just move BG on mouse over.
Loading of two different images bring you to disappearing when hover and second image loading. Better do not use JS at all. Make sprite from two images, put it as BG of DIV and write two CSS for DIV, normal and when hover.
If you have access to JQuery use hover function. If you want to change image
$('#imageid').hover(function(){
//change image or color or opacity
$(this).attr('src', newImageSrc);
});
add this function in document ready function.

Categories