adding css to custom reusable function - javascript

i created a function in jQuery which lets me create a lightbox as following:
var lightbox = create_lightbox(params);
I would like to expand this function so i can add custom css to it and make it look like a feel in any given circumstance. I would prefer to be able to do the folowing:
lightbox.css = {
"background-color" : "red",
etc...
}
What would be the best way to do this and how would i iterate over the css elements inside my function?
tyvm

Create your function to take an object with all the values you want to add to your lightbox's css property, then add in your defaults with jQuery's extend.
function create_lightbox(params, css){
css = $.extend({ "background-color": "default val"}, css);
lightbox.css = css;
}
If you really want to loop over all the properties in css, you could use a for in loop
function create_lightbox (params, css) {
css = $.extend({ "background-color": "default val"}, css);
for (cssKey in css)
lightbox.css[cssKey] = css[cssKey];
}

Just use CSS as CSS should be used: In a <style>-tag or a linked .css-file. The lightbox plugin uses the following dom tree;
<div id="jquery-lightbox">
<div id="lightbox-container-image-box">
<div id="lightbox-container-image">
<img id="lightbox-image" />
<div id="lightbox-nav">...</div>
</div>
</div>
</div>
So then style what you want to style. I guess you dpn't want to use different styles on each of your boxes?

You can add an element property to the lightbox class so you can modify value out of the constructor:
function lightbox() {
this.element = document.ccreateElement("div")
this.light = "light";
this.box = "box";
}
var newLightBox = new lightbox();
newLightBox.element.style.background = "#000";

Related

Inner DIV CSS style updation with Javascript

For the following styles, how does one change the value of background color using javascript.
i)Internal Style sheet and/or ii) External Style sheet
I am using the card deck slide show from https://github.com/dynamicdriverepo/carddeckslideshow
div.stackcontainer > div.inner{
background: #D7F9FF; }
One way would be to use a CSS variable (Only available in the latest browsers)
div.stackcontainer > div.inner{ background: var(--inner-bg-color, #D7F9FF); }
Then you can use JS to set the value for --inner-bg-color anywhere from div.inner or above.
document.querySelector('div.stackcontainer').style.setProperty('--inner-bg-color', 'red')
But if you can't change their CSS then you need to adjust the style for that element:
var el = document.querySelector('div.stackcontainer > div.inner');
if (el) {
el.style.backgroundColor = '#FF0000';
}
Be aware that you are now messing with the specificity values that determine what CSS to use. And, if you want to reset to the original then you need to remove the style value from that element.
var el = document.querySelector('div.stackcontainer > div.inner');
if (el) {
el.style.backgroundColor = '';
}

element properties in jQuery

i'm new to jQuery. so in javascript you can create a div and give it it's own properties like this :
var msgbubble = document.createElement('div');
msgbubble.marginTop="10px";
msgbubble.style.backgroundColor="#ccc";
is there is anyways i can create an element like this in jquery and how to append it.
Thanks.
Check this code snippet to create div element with some css properties and set other attributes using jQuery.
$(document).ready(function() {
let elem = $("div"); // create div element and reference it with `elem` variable
// Set css properties to created element
elem.css(
{
'background-color': 'red', 'marginTop': '50px',
'height': '200px', 'width': '200px'
}
);
// Set attribute to created element
elem.prop(
{
'id':'div1', 'class': 'myClass'
}
);
$('body').append(elem);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
For more info on jQuery visit https://www.w3schools.com/jquery
Hope, this small code snippet works for you.. :) :)
A small example of creating a div, setting properties, and appending it:
var msgBubble = $('<div></div>');
// set css properties
msgBubble.css({
'margin-top': '10px',
'background': '#ccc'
});
// or set html attributes
msgBubble.attr({
'data-foo': 'bar'
});
// add some text so it actually has a height
msgBubble.text('message bubble');
$('span').append(msgBubble);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span></span>
With jQuery(html) you can pass html text, which will then create an element.
var element = jQuery('<div></div>');
And if passed a second argument for attributes, jQuery(html, attributes), it will use those and set them on the element.
var element = jQuery('<div></div>',{
css:{
marginTop:'10px',
backgroundColor:'#ccc'
}
});
To append you can use the various methods like append(), appendTo().
element.appendTo(document.body);
So if you wanted to create your element, set the styles, and append the element in one go you would combine all of these like so:
jQuery('<div></div>',{
css:{
marginTop:'10px',
backgroundColor:'#ccc'
},
text:"Some text to go into the element"
}).appendTo(document.body);
jQuery simply uses the .append() method, though it also has .appendTo(), which functions the same way, although the two are syntactically different.
$("span").append("Appended text");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span></span>
Ass for the actual stylisation, that can be done directly through the .css() property:
el.css('margin-top', '10px');
el.css('background-color', '#ccc');
Hope this helps! :)

Disable/Enable CSS on webpage using Javascript

According to This page I was able to remove all the CSS preloaded and added on the webpage using that. I wanted to implement a button system where "onclick" = enable/disable webpage CSS even the ones pre-loaded by my web-host. I would like to eliminate the style tags to prevent lags for my website users. I prefer using the script that I have linked above unless there is another alternative that works better. Is it possible to enable CSS onclick the same button to disable? If not is it possible, can it be done with this quick? example with the preferred script below:
if (disable) {
style = "disable";
} else {
location.reload();
}
PREFERRED SCRIPT:
function removeStyles(el) {
el.removeAttribute('style');
if(el.childNodes.length > 0) {
for(var child in el.childNodes) {
/* filter element nodes only */
if(el.childNodes[child].nodeType == 1)
removeStyles(el.childNodes[child]);
}
}
}
removeStyles(document.body);
What about a different aproach?
Add initially a class to a body called 'styled' for example
<body class="styled">
use it as a main selector in your css definitions
<style>
.styled a { ... }
.styled h1 { .... }
</style>
then an example jquery script to toggle the class:
<script>
$(function() {
$('#myswitch').click(function() {
$('body').toggleClass('styled');
});
});
</script>
when class is present, the page will be styled, when absent there will be no styling.
Of coures there could be better aproach, but this is the first thing which pops up in my mind
To remove all style on an element, you could do
function removeStyles(el) {
el.style = {};
}
If you want to enable/disable the CSS on the page, then the goal is not to merely remove all the styles on the page, but you will need to save them somewhere also so they can be recalled when the user re-clicks the button. I would recommend having jQuery to help you with this, and it could be done the following way:
var style_nodes = $('link[rel="stylesheet"], style');
style_nodes.remove();
$('*').each(function(num, obj) {
var style_string = $(obj).attr("style");
if (style_string) {
$(obj).data("style-string", style_string);
$(obj).attr("style", "");
}
});
Now you've saved the stylesheets and style DOM nodes inside of style_nodes, and the actual style attribute inside of a jQuery data attribute for that specific DOM node. When you click to add the CSS back to the page, you can do the following:
$('head').append(style_nodes);
$('*').each(function(num, obj) {
if ($(obj).data("style-string"))
$(obj).attr("style", $(obj).data("style-string"));
});
Check out this JS Fiddle I put together to demonstrate it:
https://jsfiddle.net/5krLn3w1/
Uses JQuery, but I'm sure most frameworks should give you similar functionality.
HTML:
<h1>Hello World</h1>
Turn off CSS
Turn on CSS
JS:
$(document).ready(function() {
$('a#turn_off').click(function(evt) {
evt.preventDefault();
var css = $('head').find('style[type="text/css"]').add('link[rel="stylesheet"]');
$('head').data('css', css);
css.remove();
});
$('a#turn_on').click(function(evt) {
evt.preventDefault();
var css = $('head').data('css');
console.info(css);
if (css) {
$('head').append(css);
}
});
});
CSS:
body {
color: #00F;
}
h1 {
font-size: 50px;
}

How to dynamically create a css style rule that is overridable by earlier rules

I have been using jss in my project to do dynamic styles. This has worked great for the most part, but I want to do something it seems to not help with.
I want to be able to create a set of main style rules first, then create a set of default style rules that can be overridden by the main style rules if they conflict. Example:
<div class="mainClass1 defaultClass1">text</div>
<script>
jss.set('.mainClass1', {
color: 'red'
})
jss.set('.defaultClass1', {
color: 'green'
})
</script>
I want the outcome to be that the text is red, but the way jss operates, the text comes out green. I was hoping I could somehow create two dynamic stylesheets, the "default" sheet being first, and the "main" sheet being second (so that main overrides default). Is this possible?
Update - I confirmed a technique that works with raw javascript:
var styleNode = document.createElement('style');
styleNode.type = 'text/css';
styleNode.rel = 'stylesheet';
document.head.appendChild(styleNode);
//styleNode.sheet.insertRule("#A" + ' { color:green; }', 1);
var styleNode2 = document.createElement('style');
styleNode2.type = 'text/css';
styleNode2.rel = 'stylesheet';
document.head.appendChild(styleNode2);
styleNode2.sheet.insertRule("#A" + ' { color:green; }', 0);
styleNode.sheet.insertRule("#A" + ' { color:red; }', 0);
The element with id 'A' remains green even after the red style is added on the earlier stylesheet. Now I'm just wondering if I can do this with jss or if I need to roll something of my own.
Why does this not work?
var jss1 = jss.forDocument(document)
var jss2 = jss.forDocument(document)
jss2.set('#A', {
color: 'green'
})
jss1.set('#A', {
color: 'red'
})
A brief inspection of the jss source leads me to believe that your answer lies in creating different stylesheets. From my brief perusal it seems that CSS in stylesheets created later override CSS in previously created stylesheets.
"Read the source"
Using CSS selectors
You can do this very simply, just use the multiple classes selector:
jss.set('.defaultClass1.mainClass1', {...});
This has a higher class specificity than the .defaultClass selector.
Using the JSS-extend plugin
This JSS plugin simplifies extending styles. For example you can do this (copied from an example in the repository.
var button0 = {
padding: '20px',
background: 'blue'
}
var redButton = {
background: 'red'
}
window.styles = {
button0: button0,
button1: {
extend: [button0, redButton],
'font-size': '20px'
}
}
This registers the button0and button1 styles to the current window (just like linking a CSS file).
Allllright, I figured out how to do it with jss:
<div id="a">A div</div>
<script>
var jss1 = jss.forDocument(document)
jss1.defaultSheet = jss1._createSheet()
var jss2 = jss.forDocument(document)
jss2.defaultSheet = jss2._createSheet()
jss2.set('#A', {
color: 'green'
})
jss1.set('#A', {
color: 'red'
})
</script>
I found out jss lazily creates its sheet. So if you want to ensure the order of the stylesheets, you need to create them up front with _createSheet.

How to set input:focus style programatically using JavaScript

I'm building a UI library in JS that can, without relying on any CSS stylesheets, create UI components, stylised from code. So far, it's been quite easy, with exception of styling different control states (such as input:focus one).
Code that I use to create input field:
function newInput()
{
var ctr = docmuent.createElement("input");
ctr.setAttribute("type","text");
ctr.setAttribute("value", some-default-value);
ctr.style.fontFamily = "sans-serif,helvetica,verdana";
/* some font setup here, like color, bold etc... */
ctr.style.width = "256px";
ctr.style.height = "32px";
return ctr;
}
Styling it for default state is easy. However I am unsure how to set style for states such as focused, disabled or not-editable.
If I'd be having CSS stylesheets included in the project that would be easily sorted out. However I can't have any CSS files included, it must be pure JS.
Does anyone know how to set style for an input field state (eg. input:focus) straight from JS code?
No JQuery please :-) Just straight-up JS.
Thanks in advance!
You would need to add an event listener to the element in order to change the style of it. Here is a very basic example.
var input = document.getElementById("something");
input.addEventListener("focus", function () {
this.style.backgroundColor = "red";
});
<input type="text" id="something" />
Other alternative would be to build a stylesheet for the page.
Something like this:
var styles='input:focus {background-color:red}';
var styleTag=document.createElement('style');
if (styleTag.styleSheet)
styleTag.styleSheet.cssText=styles;
else
styleTag.appendChild(document.createTextNode(styles));
document.getElementsByTagName('head')[0].appendChild(styleTag);
This way you will have clean separation of css styles from the scripts and so the better maintenance.
Use CSS Variables if possible
It's 2022 and there are more simple solutions to this problem than adding event listeners all over the place that may never get cleaned up.
Instead if you have control over the CSS simply do this in your CSS:
.my-class {
--focusHeight: 32px;
--focusWidth: 256px;
}
.my-class:focus {
height: var(--focusHeight);
width: var(--focusWidth);
}
Then in your JavaScript it's as simple as using setProperty to update the variables:
const el = document.getElementById('elementId');
el.style.setProperty('--focusHeight', newFocusHeight);
el.style.setProperty('--focusWidth', newFocusWidth);
At first, create your input:
<input type="text" id="myElementID" />
Then add the javascript the following javascript:
const element = document.getElementById("myElementID");
// Add a box shadow on focus
element.addEventListener("focus", (e) => {
e.target.style.boxShadow = "0 0 0 3px #006bff40";
});
// Remove the box shadow when the user doesn't focus anymore
element.addEventListener("blur", (e) => {
e.target.style.boxShadow = "";
});
A quick oneliner, which dynamically appends a style tag to the
body.
document.body.innerHTML += '<style>#foo:focus {background-color:gold}</style>'
<input id="foo"/>
let input = document.querySelector(".input-text");
let label = document.querySelector('.fields-label');
input.addEventListener('focus', function(e){
label.classList.add('is-active');
})
input.addEventListener('blur', function(e){
if(input.value === "") {
label.classList.remove('is-active');
}
})
label.is-active{
color:red;
}
<div class="input-fields">
<label class="fields-label">Last Name</label>
<input type="text" class="input-text">
</div>

Categories

Resources