Change a background image of a style in css using javascript - javascript

Trying to change the background image of a div class background in CSS using javascript based on a hard-coded variable: See Function below:
<script type="text/javascript">
function checkLocation() {
var loctype="UH";
if(loctype=localonly)
document.getElementsByClassName('dropdown-content').style.backgroundImage="url(./img/LocalConn.jpg)";
else if(loctype=UH)
document.getElementsByClassName('dropdown-content').style.backgroundImage="url(./img/UHConn.jpg)";
else
document.getElementsByClassName('dropdown-content').style.backgroundImage="url(./img/MoodleUHConn.jpg)";
}
</script>
Called in HTML page see code below:
<div class="dropdown">
<button class="dropbtn"></button>
<div class="dropdown-content">
<div class="media">
<div class="media-left">
<script type="text/javascript">checkLocation();</script>
</div>
</div>
.CSS Code for the drop-down content class
/* The container <div> - needed to position the dropdown content */
.dropdown {
float: right;
position: relative;
display: inline-block;
}
/* Dropdown Content (Hidden by Default) */
.dropdown-content {
display: none;
position: absolute;
right:0px;
margin-top:67px;
margin-right:20px;
background-color: #f9f9f9;
min-width: 125px;
height:150px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
background-image:url(../img/LocalConn.jpg);
}
Please help as this isn't working must be something staring at my face but can't figure any help appreciated??

These lines, e.g.
document.getElementsByClassName('dropdown-content')[0].style.backgroundImage="url(./img/MoodleUHConn.jpg)";
need to have quotes inside url():
document.getElementsByClassName('dropdown-content')[0].style.backgroundImage="url('./img/MoodleUHConn.jpg')";
Also, change this css
background-image:url(../img/LocalConn.jpg);
to
background-image:url('../img/LocalConn.jpg');

The problem is document.getElementsByClassName() will always return an Array of HTML elements. So, you need to apply style to the HTML element not the array. And localonly is undefined
Your <script> should be like this
<script type="text/javascript">
function checkLocation() {
var loctype="UH";
if(loctype=localonly)
document.getElementsByClassName('dropdown-content')[0].style.backgroundImage="url(./img/LocalConn.jpg)";
else if(loctype=UH)
document.getElementsByClassName('dropdown-content')[0].style.backgroundImage="url(./img/UHConn.jpg)";
else
document.getElementsByClassName('dropdown-content')[0].style.backgroundImage="url(./img/MoodleUHConn.jpg)";
}
</script>

Your function should look like this:
function checkLocation(){
var loctype = "UH"; //if your setting variable (loctype) statically then there shouldn't be any logic, because it will always return TRUE for (loctype === "UH")
var image = (loctype === "UH") ? "url('./img/MoodleUHConn.jpg')" : (loctype === "localonly") ? "url('./img/LocalConn.jpg')" : "url('./img/MoodleUHConn.jpg')";
document.getElementsByClassName('dropdown-content')[0].style.backgroundImage = image;
}
If your just trying to trigger the event, you don't need an <a> tag you can just use a <div> tag and attach an onclick event listener like so:
<div onclick="checkLocation()">Toggle Background Image</div>
also in your CSS the background-image: property in the .dropdown-content class needs quotes around the path like so:
background-image: url('../img/LocalConn.jpg');

Related

Toggle or Show/Hide

I need help toggling overlays with multiple divs. I don't want to have a separate function for each one (there's 6 with 6 different overlay popups). The onclick div will reveal the overlay popup. Help is appreciated!
I need help toggling overlays with multiple divs. I don't want to have a separate function for each one (there's 6 with 6 different overlay popups). The onclick div will reveal the overlay popup. Help is appreciated!
function on() {
document.getElementById("overlay").style.display = "block";
}
function off() {
document.getElementById("overlay").style.display = "none";
}
#overlay {
position: fixed;
display: none;
width: 100%;
height: 100%;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0,0,0,0.8);
z-index: 2;
cursor: pointer;
}
#text{
position: absolute;
top: 50%;
left: 50%;
font-size: 1rem;
color: white;
transform: translate(-50%,-50%);
-ms-transform: translate(-50%,-50%);
}
<!-- //DIV -->
<div class="row ">
<div class="col-md-6 col-lg-4 d-flex align-items-stretch" onclick="on()">
<div class="card mb-3">
<img src="img/ballet.jpg" class="embed-responsive w-100 classpic" alt="...">
<div class="card-body">
<h5 class="card-title">BALLET</h5>
</div>
</div>
</div>
<!-- //POPUP -->
<div id="overlay" onclick="off()">
<div id="text">
<h3>Ballet</h3>
<p>Ballet is an artistic dance form performed to music using precise and highly formalized set steps and gestures.
Classical ballet, which originated in Renaissance Italy and established its present form during the 19th century,
is characterized by light, graceful, fluid movements and the use of pointe shoes.
</p>
<h4>Shedule:</h4>
<p>Ages 4-8: Thursdays • 4PM<br>
Ages 9-14: Fridays • 7PM</p>
</div>
</div>
There's a problem with your approach, namely, when an element has display:none it is removed from the html tree and cannot receive a click event. Also, no two elements can share the same id attribute and so your function cannot be applied by reference to an id directly.
I've made a working snippet that achieves what I think you are after. There are undoubtedly others that would work but it's quite straight forward and works.
Firstly, arrange each of your alternative div pairs (one hidden, one visible) inside a parent div and give it a class name. This has the advantage that, if you size the container div appropriately, the content will not jump about when you swap the hidden div for visible and vice versa. Next, give classes to distinguish the (initially) hidden content from the visible div. Your markup pattern then will be repeats of:
<div class='container'>
<div class='main'>my first main content</div>
<div class='hidden'>my first hidden content </div>
</div>
In the style sheet, set the class display properties:
.hidden {
display: none;
}
.main {
display: block;
}
Then, set up a click event listener in javascript. This will take a click event from anywhere on the page.
document.addEventListener('click', event => {
})
inside the event listener, place an if block to test whether the click event was received by an element that was inside a div of .container class:
if (event.target.parentElement.className=='container') {
}
I slightly modified this, see edit note and bottom.
If the click event got that far, the click must have been recieved by the visible div inside that container (since the hidden one cannot receive click events and they are the only two elements present.
So you can go ahead and swap the classes applied to the visible div that received the click:
event.target.classList.add('hidden');
event.target.classList.remove('main');
You now have to do the opposite to the other div in the container class to make that sibling visible. The problem is, you don't know whether the hidden class was the first child, or the second child of the container div. What you do know for sure, is that the other div is a sibling of the div you just made invisible.
So we can test to see if there is a next sibling using a conditional:
if (event.target.nextElementSibling) {
event.target.nextElementSibling.classList.add('main');
event.target.nextElementSibling.classList.remove('hidden');
}
If the hidden div followed the visible one, a nextElementSibling will be found and the classes swapped. If no nextElementSibling was found, we know the other div had to come before the one we already hid.
so, an else extension of that if block can be added to switch the classes on the previousElementSibling:
...} else {
event.target.previousElementSibling.classList.add('main');
event.target.previousElementSibling.classList.remove('hidden');
} // end else;
And you're done!
I wanted to explain the logic in detail to make sure you know what's going on, but it's not that complicated.
The advantage of an approach like this is that the single event listener will cope with 1, 2, or 1,000 pairs of divs and none need any special IDs or anything other than an initial class of .main or .hidden (and that they be grouped inside a .container div.
document.addEventListener('click', event => {
if (event.target.parentElement && event.target.parentElement.className=='container') {
event.target.classList.add('hidden');
event.target.classList.remove('main');
if(event.target.nextElementSibling) {
event.target.nextElementSibling.classList.add('main');
event.target.nextElementSibling.classList.remove('hidden');
} else {
event.target.previousElementSibling.classList.add('main');
event.target.previousElementSibling.classList.remove('hidden');
} // end else;
} // end parentElement if;
}) // end click listener;
.hidden {
display: none;
border: 1px solid red;
margin: 5px;
}
.main {
display: block;
border: 1px solid black;
margin: 5px;
}
<div class='container'>
<div class='main'>my first main content</div>
<div class='hidden'>my first hidden content </div>
</div>
<div class='container'>
<div class='main'>my second main content</div>
<div class='hidden'>my second hidden content </div>
</div>
Edit the conditional to detect whether the parent element of the click event was a .container div was modified to check that the event target has a parent AND that the parent is a .container div. This prevents an error if a click is received anywhere outside of the container div.
** Displaying an Opaque Overlay in Response to Click **
Again, this solution allows the functionality to be applied to limitless div elements without the need for independent ids. Again, two classed .main and .hidden are used to decide which div has been clicked from a single event listener applied to the document rather than to multiple divs.
The basic process of displaying, and then re-hiding the (originally hidden) .overlay div is very simple:
if (element.className == 'main') {
element.parentElement.getElementsByClassName('overlay')[0].classList.remove('hidden');
}
if (element.className == 'overlay') {
element.classList.add('hidden');
}
However, a problem arises because of the use of class names, rather than ids. Namely, when the overlay is displayed, a click on it may be received by a descendent element that does not have the class name .hidden. To work properly, every descendent of the overlay div would have to be given the .hidden class and the class swapped applied for ever element inside the .hidden div. This could get very complicated if the div had many child elements (perhaps with their own descendents).
Instead, when a click is received, the target element is inspected to see if it has a relevant class (main or hidden). If it does, the script flows to the simple class switching blocks. If it has no, or a different class name however, a do-while loop examined the parent element of the click to see if it was contained in a relevant (main or hidden) class. The loop continues searching up the document tree until either a relevant element is found, or there are no more parent elements to examine.
If a parent is found to have the required class name, a reference to the element is passed onto the class switching block.
do {
if (element && (element.className == 'overlay' || element.className == 'main')) {
// foundElementClassName = element.className;
break;
} // end if;
if (element.parentElement) {
element = element.parentElement;
} else {
break;
}
} while (element.className != "overlay" || element.className != "main");
The following working snippet demonstrates the functionality. In it, three divs (coloured pink) have an associated (initially) hidden overlay div, while a fourth div has no associated overlay and should ignore clicks.
If a click is made on a pink div, it's specific overlay appears. A click anywhere on the overlay dismisses it, regardless of whether the click was received by the overlay div itself, or by a child element or deeper descendent (e.g. clicking on the text of the overlay (which is in a child h2 element still allows the correct .overlay div to have its styles switched to hide it again.
document.addEventListener('click', (event) => {
let element = event.target;
do {
if (element && (element.className == 'overlay' || element.className == 'main')) {
// foundElementClassName = element.className;
break;
} // end if;
if (element.parentElement) {
element = element.parentElement;
} else {
break;
}
} while (element.className != "overlay" || element.className != "main");
// end do-while loop;
// if a relevant element was found, the element object is stored in element variable;
if (element.className == 'main') {
element.parentElement.getElementsByClassName('overlay')[0].classList.remove('hidden');
}
if (element.className == 'overlay') {
element.classList.add('hidden');
}
}) // end click event listener;
.main {
display: block;
width: 50%;
margin: 10px;
border: 1px solid black;
background: pink;
}
.overlay {
position: absolute;
display: flex;
align-items: center;
justify-content: center;
top: 0px;
left: 0px;
width: 100%;
min-height: 100%;
bottom: auto;
z-index: 1;
background: rgba(255,255,0,0.7);
padding: 20px;
}
.hidden {
display: none;
}
.other {
display: block;
width: 50%;
margin: 10px;
border: 1px solid black;
background: yellow;
}
<div class="container">
<div class="main">Content of div 1. Content of div 1. Content of div 1. Content of div 1. Content of div 1. Content of div 1. Content of div 1. Content of div 1 </div>
<div class="overlay hidden"><h1>overlay for first pink div</h1> </div>
</div>
<div class="other">
some other content that doesn't have an associated overlay and that should ignore clicks.
</div>
<div class="container">
<div class="main">Content of div 2. Content of div 2. Content of div 2. Content of div 2. Content of div 2. Content of div 2. Content of div 2. Content of div 2. Content of div 2. Content of div 2.</div>
<div class="overlay hidden"><h1>overlay for SECOND pink div</h1> </div>
</div>
<div class="container">
<div class="main">Content of div 3. Content of div 3. Content of div 3. Content of div 3. Content of div 3. Content of div 3. Content of div 3. Content of div 3. Content of div 3. Content of div 3. </div>
<div class="overlay hidden"><h1>overlay for Third pink div</h1> </div>
</div>

changing element>element style inside javascript function

I have this style showing a card, and I want to change it inside the function after picking the card. how can I use style.background = '#FFF'; on div#memory_board > div type?
div#memory_board > div{
background:black;
border:#000 1px solid;
width:71px;
height:71px;
float:left;
margin:10px;
padding:20px;
font-size:64px;
cursor:pointer;
text-align:center;
}
You could add the following to your CSS, which would be applied to the "picked" card <div>:
div#memory_board > div.picked {
background: #fff;
}
Once you've added the above to your style sheet, you would then add the picked class to the <div> elements directly under #memory_board element which would produce the desired visual result.
<div id="memory_board">
<div></div> <!-- regular style -->
<div></div> <!-- regular style -->
<div class="picked"></div> <!-- regular style with "picked" appearance -->
</div>
Update
To apply the picked class to the clicked <div> you need to update your cardIsSelected() function in your script:
function cardIsSelected(event, letter)
{
/* This will cause "picked" class to be added to the div being
clicked */
event.currentTarget.classList.add('picked');
/* Leave existing code */
}
You will also need to pass the event object to cardIsSelected by updating this line of your code as well:
output += '<div id="card'+i+'" onclick="cardIsSelected(event, \''+memory_array[i]+'\')">'+memory_array[i]+'</div>';
Here is a working CodePen

CSS Sprites loading

I want to change the src attribute of img inside of my span with id="slider_arrow",
<span id="slider_arrow">
<img />
</span>
each time my jquery function runs:
$("#0").click(function () {
/*Rest of the function*/
var arrow = document.getElementById('slider_arrow');
/*I want to add different slider_arrow's sprite each time i call this function*/
});
CSS:
.red_arrow_sprite{
width:25px;
height:12px;
background:url("/Images/arrows.png") 0 0px;
}
.yellow_arrow_sprite{
width:25px;
height:12px;
background:url("/Images/arrows.png") -26px 0px;
}
.black_arrow_sprite{
width:25px;
height:12px;
background:url("/Images/arrows.png") -51px 0px;
}
My CSS Sprite file has 75px width and 12px of height. Each picture has 25px/12px.
The questions are:
1) Do I have correctly written CSS rules?
2) What I need to use to change src of img inside of span?
Thanks!
Fiddle: http://jsfiddle.net/vtkppwuc/3/
$("#0").click(function () {
var classes = ['red_arrow_sprite','yellow_arrow_sprite','black_arrow_sprite'];
var $span = $('#slider_arrow');
$span.attr('class', (classes[($.inArray($span.attr('class'), classes)+1)%classes.length]));
});
DEMO: http://jsfiddle.net/vtkppwuc/6/
Remove the image inside span and use jQuery for setting the css class to your Slider, try this code
<span id="slider_arrow" class="red_arrow_sprite">
</span>
$("#0").click(function () {
var item = $('#slider_arrow');
if (item.hasClass('red_arrow_sprite')){
item.removeClass('red_arrow_sprite').addClass('yellow_arrow_sprite');
} else if (item.hasClass('yellow_arrow_sprite')){
item.removeClass('yellow_arrow_sprite').addClass('black_arrow_sprite');
} else {
item.removeClass('black_arrow_sprite').addClass('red_arrow_sprite');
}
});

How to change the theme color in less css using javascript/jquery

am using the below less css to change different theme color
#lightRed: #fdd;
#lightGreen: #dfd;
#lightBlue: #ddf;
#defaultThemeColor:#lightBlue;
#header{
.wrapper();
width:#defaultWidth;
height:80px;
margin-bottom:20px;
background:#defaultThemeColor;
}
#menu{
background:#defaultThemeColor;
}
And html is as follows:
<div id="swatch">
<ul>
<li>theme1</li>
<li>theme2</li>
<li>theme3</li>
</ul>
</div>
when theme1 is clicked #lightRed theme should be loaded, for theme2 #lightBlue and for theme3 #lightGreen
Please let me know how should be my javascript/ jquery to change the theme color on click
you could try using less.js functions like:
less.refreshStyles()
or
less.modifyVars()
you can maybe read some more on this here: Dynamically changing less variables
Something along this lines with jQuery and modifyVars on a .click event might work:
$('.theme_option').click(function(event){
event.preventDefault();
less.modifyVars({
'#defaultThemeColor': $(this).attr('data-theme')
});
});
using the on-click event to change the background color
this is example for changing the background color using on change..pls check it out [Example][http://jsfiddle.net/6YVes/]
If you just want to change the background color onclick li's, assign each li a class and trigger a jQuery click event on every class like below:
HTML:
<div id="swatch">
<ul>
<li><a class="red" href="">theme1</a></li>
<li><a class="green" href="">theme2</a></li>
<li><a class="blue" href="">theme3</a></li>
</ul>
</div>
JS:
$('.red').click(function(){
$(this).css('background-color',"red")
});
$('.green').click(function(){
$(this).css('background-color',"red")
});
$('.blue').click(function(){
$(this).css('background-color',"blue")
});
Note that lesscss is a Css that must be compilerd. That means you can not modify directly the behaviour of your lesscss but you can with css compiled. Browsers do no understand lesscss you have to keep it in mind.
So, I think the best way to do this is using two classes on the object you want to modify, one with the shape and another with the theme. In this way you can switch from one to anothr by modifying using jQuery the theme class. Imagine something like:
lesscss:
.theme-1 {
//Here goes your theme colors
}
.theme-2 {
//Here goes more theme colors and rules
}
#header {
.wrapper();
width:#defaultWidth;
height:80px;
margin-bottom:20px;
background:#defaultThemeColor;
}
And your html:
<div id="header" class="theme-1"/>
<button onclick="$('.theme-1').removeClass('theme-1').addClass('theme-2');" name="Change to theme 2"/>
<button onclick="$('.theme-2').removeClass('theme-2').addClass('theme-1');" name="Change to theme 1"/>
Hope it helps.
As prem suggested, it would be best to apply a class to each theme
CSS:
/* -- [ light blue theme (default) ] ---------- */
#header, #header.lightblue {
background: #ddf;
height: 80px;
margin-bottom: 20px;
width: 300px;
}
#menu, #menu.lightblue {
background: #ddf;
}
/* -- [ light red theme ] ---------- */
#header.lightred {
background: #fdd;
height: 95px;
margin-bottom: 10px;
width: 400px;
}
#menu.lightred {
background: #fdd;
}
/* -- [ light green theme ] ---------- */
#header.lightgreen {
background: #dfd;
height: 72px;
margin-bottom: 15px;
width: 290px;
}
#menu.lightgreen {
background: #dfd;
}
This way, to change each theme, you just have to change the class of the container object. Say the container object is the document body, then the body's class be changed to the desired theme.
HTML:
<div id="swatch">
<ul>
<li><a class="theme_option" data-theme="red" href="#">theme1</a></li>
<li><a class="theme_option" data-theme="green" href="#">theme2</a></li>
<li><a class="theme_option" data-theme="blue" href="#">theme3</a></li>
</ul>
</div>
JavaScript (jQuery):
jQuery('a.theme_option').click(function(e){
e.preventDefault();
var theme_class = jQuery(this).attr('data-theme');
jQuery(body).attr('class', theme_class);
}
the variables in css is a draft now!
http://www.w3.org/TR/css-variables/
Create classes by each color
Store class into local storage
change it using javascript function
<!DOCTYPE html>
<html lang="en" class="theme_name_1">
<head>
<style>
.theme_name_1{
color: #FFFF;
}
.theme_name_2{
color: #000;
}
</style>
</head>
<body>
<button id="switch" onclick="changeTheme()">Switch</button>
<script>
/* Script Save theme local storage to first load */
if (localStorage.getItem('theme') === 'theme_name_2') {
setTheme('theme_name_1');
} else {
setTheme('theme_name_2');
}
function setTheme(theme_name) {
localStorage.setItem('theme', theme_name);
document.documentElement.className = theme_name;
}
/*Change theme button click */
function changeTheme() {
if (localStorage.getItem('theme') === 'theme_name_2') {
setTheme('theme_name_1');
} else {
setTheme('theme_name_2');
}
}
</script>
</body>
</html>

javascsript : adding plus/minus icon to spry collapsible panel in dreamweaver

I'm working on modifying a website which has a chart of FAQs which have has a question link.
If question link is clicked, it reveals the answer in a drop down.
My goal is to swap out a plus icon image with a minus icon next to the linked text for the drop down reveal action.
the FAQs use Spry Collapsible Panel (sprycollapsiblepanel.js) to manage the show/hiding from the link. before I go about modifying the code in the javascript source code, I was wondering if there was an easier way of doing this through dreamweaver someone might be aware of.
thanks in advance.
UPDATE:
the html calling the show/reveal actions are:
<div class="CollapsiblePanel">
<div id="CollapsiblePanel1" class="CollapsiblePanel">
<div class="CollapsiblePanelTab" tabindex="1">Fax to E-Mail</div>
<div class="CollapsiblePanelContent">Here is the text content as it relates to Fax to E-Mail</div>
</div>
</div>
The construct the actions for the drop down, Spry requires the following at the bottom of the page:
<script type="text/javascript">
var CollapsiblePanel1 = new Spry.Widget.CollapsiblePanel("CollapsiblePanel1", {contentIsOpen:false});
var CollapsiblePanel2 = new Spry.Widget.CollapsiblePanel("CollapsiblePanel2", {contentIsOpen:false});
var CollapsiblePanel3 = new Spry.Widget.CollapsiblePanel("CollapsiblePanel3", {contentIsOpen:false});
</script>
In SpryCollapsiblePanel.css, amend the following style rules:
.CollapsiblePanelTab {
font: bold 0.7em sans-serif;
background-color: #DDD;
border-bottom: solid 1px #CCC;
margin: 0px;
padding: 2px 2px 2px 25px;
cursor: pointer;
-moz-user-select: none;
-khtml-user-select: none;
}
This increases the padding on the left to make room for the image.
Then add the images to the following rules:
.CollapsiblePanelOpen .CollapsiblePanelTab {
background-color: #EEE;
background-image: url(images/plus.gif);
background-position:left top;
background-repeat: no-repeat;
}
.CollapsiblePanelClosed .CollapsiblePanelTab {
background-image: url(images/minus.jpg);
background-position:left top;
background-repeat: no-repeat;
/* background-color: #EFEFEF */
}
THe plug ins adds a class to each panel title when is opened and when is closed, these are "CollapsiblePanelOpen" and "CollapsiblePanelClosed" accordingly. With that you can use CSS to add the +- effect with a background image perhaps.
onclick switch an image then onclick of something else switch back to + sign
If it's an image, and you don't want to change the source code, and you want to use javascript, you'll need to change the src property of the image.
// Grab the img object from the DOM
var img = document.getElementById("theImageId");
// If it's the plus pic, switch for minus, and vice versa.
if(img.src == "plus.png") {
img.src = "minus.png";
}
else {
img.src = "plus.png";
}
You can put this code in wherever you need (in an onclick or a function or whatever). Also, the URLs for the images will obviously need to be updated.
Easy fix with some simple JavaScript.
Add the following script:
<script type="text/javascript">
<!--
function name ()
{
var img = document.getElementById("imgid");
if (img.src == "plus.png") {
img.src = "minus.png";
}
else {
img.src = "plus.png";
}
}
//-->
</script>
When that's done look at the div defining the collapsible panel. It looks something like this:
<div id="CollapsiblePanel1" class="CollapsiblePanel">
<div class="CollapsiblePanelTab" tabindex="0">Name <img src="url.com/minus.png" id="imgid"></div>
<div class="CollapsiblePanelContent">content</div>
All you need for this to work is to add onclick="name();" to the syntax:
<div id="CollapsiblePanel1" class="CollapsiblePanel">
<div class="CollapsiblePanelTab" tabindex="0" onclick="name();">Name <img src="url.com/minus.png" id="imgid"></div>
<div class="CollapsiblePanelContent">content</div>

Categories

Resources