Changing background colour of specific select2 through javascript - javascript

In a web form, I'm using two select2 control at two panel each.
I wish to change only one of the select2's background colour when it hit certain condition through javascript else it will remain its original colour.
How can I accomplish that?
I am at the stage where the css code below I found is able to modify the select2 to the result I want.
.select2-container .select2-selection{
background: yellow;
}
Any help is much appreciated.
Edited:
Adding some part of my code:
CSS
.select2-container {
position: relative;
z-index: 2;
float: left;
margin-bottom: 0;
display: table;
table-layout: fixed;
font-size: smaller;
}
Markup
<div class="container-fluid">
<div class="col-md-7">
<table>
<tr>
<td>
<select id="ddl_Select2ONE" runat="server" class="form-control select"></select>
</td>
</tr>
</table>
</div>
<div class="col-md-5">
<table>
<tr>
<td>
<select id="ddl_Select2TWO" runat="server" class="form-control select"></select>
</td>
</tr>
</table>
</div>
</div>
Javascript
pageLoad(){
configureSelect2()
}
configureSelect2(){
if(hf_value.value == "1"){
//Change only ddl_Select2ONE to yellow background
}
else{
//Change only ddl_Select2ONE to original background
}
}
Then I will perform some checking on javascript's pageload when it check a hidden field value for conditional enable.

You can use:
document.getElementById('idOfElement').classList.add('select2-container')`;
Or using jquery:
$("#idOfElement").addClass("select2-container");
$("#idOfElement").addClass("select2-selection");

Ok your javascript should look something like this:
document.querySelector('#ddl_Select2ONE').style.background = "Yellow";
And in your else clause:
document.querySelector('#ddl_Select2TWO').style.background = "Yellow";

Try this
function declaration syntax was wrong.
use with classList function
//add in your js
function pageLoad() {
configureSelect2()
}
function configureSelect2() {
if (hf_value.value == "1") {
document.getElementById("ddl_Select2ONE").classList.add("yellow");
} else {
document.getElementById("ddl_Select2ONE").classList.remove("yellow");
}
}
//add in your css
.yellow{
background-color:yellow !important;
}

Solved and solution provided here :
What I need was the "!important" in css class and finding the span I need to add the css class to.
CSS
.yellowBackground{
background: yellow !important;
}
javascript
function pageLoad(){
configureSelect2()
}
function configureSelect2(){
td_Name = document.getElementById("<%=td_Name.ClientID %>");
if (hf_Value.value == "1") {
($(td_Name).find('span')).addClass('yellowBackground');
}
else {
($(td_Name).find('span')).removeClass('yellowBackground');
}
}
Hope this helps!

Related

Change class bg if checkbox is checked

I'm working on my portfolio website and need some help with a bit jQuery code. I want a parent class to react to the checkbox in it. In this case, the background color needs to change to #000 when the checkbox is active/checked.
I don't know what line of code to add to make my class react to the checkbox. I've searched on google on how to do it but didn't get much wiser. It's probably a really small thing but I would hope to get some help from you guys.
$("input[type='checkbox']").change(function() {
if ($(this).is(":checked")) {
$(this).parent();
} else {
$(this).parent();
}
});
.product {
background-color: #ccc;
/* needs to change to #000 when active */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<div class="product">
<input class="check" type="checkbox" name="logo"> Logo
</div>
Basically you create a second (more specific) css selector for the active state, then you use your jQuery to toggle that state/class based on the checkbox value.
https://jsbin.com/betafupogu/1/edit?html,css,js,output
CSS
.product {
background-color: #ccc; /* needs to change to #000 when active */
}
.product.active {
background-color: #000;
}
jQuery
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$("input[type='checkbox']").change(function(){
if($(this).is(":checked")){
$(this).parent().addClass('active');
}else{
$(this).parent().removeClass('active');
}
});
</script>

How to set background color for all elements with the same class individually based on custom attribute

I have multiple elements with the class .hours and they all have a color attribute with a hex value like so: <div class="hours" color="#FFFFFF">.
How can I use jQuery to set the background color of all the elements individually so that the element over has the color #FFFFFF and the element <div class="hours" color="#666666"> gets the background color #666666?
My attempt: $('.hours').css('background-color', this.attr.color);
You can use .each to refer to every element and it's color attribute
$('.hours').each(function() {
let elem = $(this);
elem.css('background', elem.attr('color'));
});
.hours {
border: 1px solid black;
height: 100px;
width: 100px;
display: inline-block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="hours" color="#FFFFFF"></div>
<div class="hours" color="#AAAAAA"></div>
<div class="hours" color="#444444"></div>
Pure JS solution (for this jQuery is rather ineffective in my opinion...):
document.querySelectorAll('.hours').forEach(function(el) {
el.style.backgroundColor = el.getAttribute('color');
});
try with this
$('.hours').each(function(){
var t = $(this);
t.css('background-color', t.attr('color'));
});
})
$(".hours").each(function(){
let $this= $(this);
let color=$this.attr("color");
$this.css("background-color", color);
});
Not really what you asked, but the same can be achieved without JS, just with pure CSS and custom properties:
<div style="--color: green"></div>
div {
--color: #e2001a; /* default color */
background-color: var(--color);
height: 40px;
}
Example: http://jsfiddle.net/e1fwtcdz/1

Using JavaScript script multiple times

I don't believe this has been asked before. If it has I apologise as I couldn't find it.
I have an HTML table with pictures as buttons:
<td>
<button class="trigger">
<img src="D:\Elly Research\ CO2858\Presentation\Calypso_map.jpg">
</button>
</td>
<div class="modal">
<div class="modal-content">
<span class="close-button">× </span>
<img src="D:\Elly Research\CO2858\Presentation\Calypso_map.jpg">
<script src="D:\Elly Research\CO2858\Presentation\modal.js"></script>
</div>
</div>
This is controlled by a script:
var modal = document.querySelector(".modal");
var trigger = document.querySelector (".trigger");
var closeButton = document.querySelector(".close-button");
function toggleModal() {
modal.classList.toggle("show-modal");
}
function windowOnClick(event) {
if(event.target === modal){
toggleModal();
}
}
trigger.addEventListener("click", toggleModal);
closeButton.addEventListener("click", toggleModal);
window.addEventListener("click", windowOnClick);
If I copy the format of the first picture and use it for a second picture in the same table and same page, it stops working.
Does JavaScript not work like CSS where I can use multiple ID's to be controlled by one CSS value?
This is the first time I've used JavaScript with HTML and CSS.
When you do document.querySelector(".modal") you are selecting the first node that has the class "modal". Which in your case would be the div containing the first picture. And later you add the 'click' event to only the first picture.
You can use querySelectorAll, which returns a list of all the matching nodes and loop through all nodes to add the 'click' event listener like so:
const modals = document.querySelector(".modal");
modals.forEach(modal => {
modal.addEventListener('click', toggleModal)
});
I am not sure what exactly you are trying to ask. Based on my assumptions here is a small snippet. Hope it helps you.
var modal = document.getElementById("modal")
window.addEventListener("click", windowOnClick);
document.querySelector(".close-button").addEventListener("click", toggleModal)
function showImage(event){
toggleModal()
modal.getElementsByTagName("img")[0].src =event.srcElement.src
}
function windowOnClick(event){
if(event.srcElement === modal){
toggleModal()
}
}
function toggleModal(){
modal.classList.toggle("show-modal")
}
td > img{
width: 100px;
height: auto;
}
.modal{
display: none;
position: fixed;
top: 0px;
left: 0px;
width: 100%;
height: 100%;
background: rgba(0,0,0,0.8);
z-index=10;
}
.show-modal{
display: block !important;
}
.modal-content{
width: 60%;
height: auto;
margin: 0 auto;
}
.close-button{
color: white;
cursor: pointer;
}
#viewer{
width:100%;
height: auto;
}
<!doctype>
<html>
<head>
</head>
<body>
<table>
<tr>
<td>
<img src="https://i.imgur.com/GV6086A.jpg" onclick="showImage(event)" />
</td>
<td>
<img src="https://i.imgur.com/opERcp1.jpg" onclick="showImage(event)" />
</td>
</tr>
<tr>
<td>
<img src="https://i.imgur.com/lieUEvQ.jpg" onclick="showImage(event)" />
</td>
<td>
<img src="https://i.imgur.com/B63gaEQ.jpg" onclick="showImage(event)" />
</td>
</tr>
</table>
<div class="modal" id="modal">
<div class="modal-content">
<span class="close-button">× </span>
<img id="viewer">
</div>
</div>
</body>
</html>
If it is a small application, a simple solution to this could be the creation of an object of images, containing its details, like this:
//Here you can add as many properties you want for the objects
images = [{
src: "D:\Elly Research\CO2858\Presentation\Calypso_map.jpg"
},
{
src: "D:\Elly Research\CO2858\Presentation\Calypso_map_alternative.jpg"
}]
Then you could iterate over it to generate your table, or simply create your table with some ID refs, like <button id="0" class="trigger">, therefore you can access them in the event object array index with this code:
var id = event.target.id
So, to generate the img element inside the modal, you'll have something like this:
function toggleModal(event){
var id = event.target.id;
var div = document.getElementsByClassName('modal-content')[0];
div.innerHTML += '<img class="modal-image" src="'+images[id].src+'" />';
modal.classList.toggle("show-modal");
}
But make sure you destroy the img element when it already have one:
var child = div.querySelector("img");
if(child != null){
div.removeChild(child);
}
Hope it helps you!! Good luck with your study!
You can use js multiple times. Check the src of your images.
It's discussed already here -src absolute path problem.

Change a background image of a style in css using 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');

Proper way to dynamically change css properties?

I have site that, in response to user interaction, dynamically creates divs using jquery. The div will have a span inside containing a timestamp to show its creation time, and the user can click a button to show or hide the timestamp span.
I ran into the issue of, when the user selects to hide timestamps, how do you prevent future dynamically added spans from showing? In reference to this question Create a CSS rule / class with jQuery at runtime, I added a style tag in the head dynamically. However, I also intended to allow the user to be able to choose a font from a drop down list and change the font style of the text inside the divs. Following this method now seems like it would create a lot of overhead.
Both issues revolve around the same issue: change already existing element and any future dynamically created matching element's css style, but I'm not sure the method mentioned above is really the best solution?
EDIT: SNIPPET
$(function() {
$('#add').click(function() {
$('#display').append("<div><span class='time'> ex. Timestamp</span> Div text contents...</div>");
});
$('#hidetime').click(function() {
$(this).text(function(i, text) {
if (text === "Hide Time") {
$("<style>").prop("type", "text/css")
.html(".time {display: none}").appendTo("head");
return "Show Time";
} else {
$('style').remove();
return "Hide Time";
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='add'>Add</button>
<button id='hidetime'>Hide Time</button>
<div id='display'>
</div>
You've provided no code to debug, but the way you can do this is to toggle a class such as notimestamps on the container element for the whole thing.
Then in your main CSS code you can simply do something along the lines of:
.container.notimestamps span {
display:none;
}
If you're changing font styles, you can do something very similar.
Example:
.container.font-arial {
font-family: arial, sans-serif;
}
.container.font-tahoma {
font-family: tahoma, sans-serif;
}
Using your recently added example you would change it to:
$(function() {
$('#add').click(function() {
$('#display').append("<div><span class='time'> ex. Timestamp</span> Div text contents...</div>");
});
$('#hidetime').click(function() {
$('#display').toggleClass('notimestamp');
});
$('#font').change(function() {
$('#display').attr('data-font', $(this).val());
});
});
#display.notimestamp span {
display:none;
}
#display {
font-family:sans-serif;
}
#display[data-font="arial"] {
font-family:Arial;
}
#display[data-font="georgia"] {
font-family:Georgia;
}
#display[data-font="tahoma"] {
font-family:Tahoma;
}
#display[data-font="tnr"] {
font-family:"Times New Roman";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='add'>Add</button>
<button id='hidetime'>Hide Time</button>
<select id="font">
<option value="arial">Arial</option>
<option value="georgia">Georgia</option>
<option value="tahoma">Tahoma</option>
<option value="tnr">Times New Roman</option>
</select>
<div id='display'>
</div>
You can achieve it using plain javascript
Here is an example. You can add any similar styles dynamically
HTML
<div id="myDiv" style="margin: 50px 50px 50px 50px">This is a div.</div>
<br />
<button type="button" onclick="removemargin()">remove margin</button>
<button type="button" onclick="removeLeftMargin()">remove leftmargin</button>
<button type="button" onclick="removeTopMargin()">remove topmargin</button>
<button type="button" onclick="addCssMargin()">add margin by adding class (dominant here)</button>
CSS
#myDiv {
background: #EEE;
}
.myclass{
margin : 100px 10px 15px 50px !important;
background:red !important;
}
JAVASCRIPT
function removemargin() {
document.getElementById("myDiv").style.margin = "0";
}
function removeLeftMargin() {
document.getElementById("myDiv").style.marginLeft = "0";
}
function removeTopMargin() {
document.getElementById("myDiv").style.marginTop = "0";
}
function addCssMargin() {
var d = document.getElementById("myDiv");
d.className = d.className + " myclass";
}
JsFiddle

Categories

Resources