change css with knockoutjs - javascript

Lets say that I have a div with a background color of #333333, and I have an input field where the user can input their own hex value, ex: #000000, and then I want the div's background color to change to #000000 on the fly....
example:
HTML:
<div class="mydiv"></div>
css:
<style type="text/css">.mydiv { background-color:#333333; }</style>
Then when the user changes the value via an input type="text" field, when the CSS should change in the style="text/css" block.
How do I make that binding?
I can't use the in my style block, because that is not valid CSS, and I don't want to do it on my like and then insert the style here... So again, I want to change the CSS in my style block, and not add a style to my div element.
Sort of like this where they update it on the fly; http://css3gen.com/box-shadow/
When you change something, the CSS behind changes, so that you can preview your element on the fly.

Use style binding
<div data-bind='style: { "backgroundColor": CustomBGC }'>
http://jsfiddle.net/nyothecat/jKysB/3/
Edit:
Since you want to update the style, you can make use of the cascading style sheet.
Define a class with init color, then create a style tag with a text binnding. Fill this one with your new color.
In your css file:
.myClass { background-color: #f00 }
Make sure to put your css file before the following
<div id="koRoot">
<div class="myClass">
<input type='text' data-bind="value: customColor" />
</div>
<style data-bind="text: myObservableStyle(customColor)"></style>
</div>
And the javascript:
$(document).ready(function () {
var ViewModel = {
customColor: ko.observable("#f00"),
myObservableStyle: function (obs) {
return ".myClass { background-color: " + obs() + " }";
}
}
ko.applyBindings(ViewModel, document.getElementById("koRoot"));
});
http://jsfiddle.net/k97ZZ/1/

pseudohtml :
<input type="text" data-bind="value:userInput">
pseudoscript:
var MyModel=function(data){
var self=this;
self.userInput=ko.observable('#333333');
self.computedCss=ko.computed(function(){
//appends Style block to head everytime userInput changes
appendal="<style>.myClass { background-color: "+self.userInput()+";!important}</style>";
$('head').append(appendal);
}
}
myModel = new MyModel({});
ko.applyBindings(myModel);

You can use the style binding along with the value binding
<input data-bind="value: inputColor" />
<div data-bind="style: { color: inputColor()}">
Something
</div>
var viewModel = {
inputColor: ko.observable()
};
Edit
Since you want to change the style element itself use the text binding on style tag. One thing to remember that entire style will be changed so you will have to maintain valid css rules before updating the element.
<style data-bind="text:inputColor"></style>
You might want to subscribe to the inputColor observable so you can change the input to valid css before populating the style element.
This question might be relevant.

You can use virtual if binding
<style type="text/css">
<!-- ko if: someExpression -->
.mydiv { background-color:#333333; }
<!-- /ko -->
<!-- ko if: !someExpression -->
.mydiv { background-color:#000000; }
<!-- /ko -->
</style>

Related

SPA how to swap content

Cheers! Building a webpage from scratch using tornado io. I have different graphs and wanted to use some of the single page app magic. So I thought do a div and swap out the content doing:
<div id="chartType"> Chart goes here</div>
Load Graph
<div id="maincontent"></div>
<script type="text/javascript">
$('#addContent').click(function(){
$("#maincontent").replaceWith("{% include graph.html %}");
return false;
});
</script>
HTML does not seem to like the {% include graph.html %}
If I do something like $("#maincontent").load(/path/to/file) it keeps adding the content and not swapping it.
My question is how to swap the div content with different {% includes %}?
Is there a better way of doing this (Am I misusing the %includes% )?
Many thanks
I believe that $("#maincontent").load(/path/to/file); should work. I think you may be running afoul of caching, and so you may need to do this:
var setMainContent = function(path) {
$.get({
url: path,
cache: false
}, function(data){
$("#maincontent").html(data);
});
};
And then call your function in your click handler:
setMainContent(/path/to/file);
What I usually do with very simple content swaps is use css to handle it.
For instance, if I have the content I want to show originally in Div A and the content I want to replace it with in Div B, by default I will have Div A set to 'display: block' and Div B set to 'display: none'. Then, to swap the content, use javascript to set Div A to 'display: none' and Div B set to 'display: block'.
var divA = document.getElementById('divA');
var divB = document.getElementById('divB');
function hideDivA() {
divA.style.display = 'none';
}
function showDivB() {
divB.style.display = 'block';
}
function swapContent() {
hideDivA();
showDivB();
}
#divA {
background: #74CFAE;
color: #000;
display: block;
}
#divB {
background: #555;
color: #fff;
display: none;
}
<div id='content-wrap' onclick='swapContent()'>
<div id='divA'>Div A (initially visible content)</div>
<div id='divB'>Div B (initially not visible content)</div>
</div>
Depending on your use case, you can also create a template and assign that into your DOM.
For instance.
<div id="runtime_area"></div>
<script type="text/html" id="page1">
<b>Banner</b>
</script>
Then later
document.getElementById("runtime_area").innerHTML = document.getElementById("page1").innerHTML

Update textarea placeholder text color dynamically with jQuery [duplicate]

Is it possible to use "::-webkit-input-placeholder" with jQuery to set a color for the placeholder text?
Something like this:
$("input::-webkit-input-placeholder").css({"color" : "#b2cde0"});
You can't really modify pseudo-selectors with JavaScript. You'll have to modify an existing a <style> element.
If possible, make a class:
.your-class::-webkit-input-placeholder {
color: #b2cde0
}
And add it to the element:
$('input').addClass('your-class');
If you don't have a stylesheet, and want to inject CSS dynamically you can use the following:
$('body').append('<style>.my_class::placeholder{color:red}</style>')
Just use my_class and the color for the placeholder.
It's handy to have a general purpose function:
function change_placeholder_color(target_class, color_choice) {
$("body").append("<style>" + target_class + "::placeholder{color:" + color_choice + "}</style>")
}
Usage:
change_placeholder_color('.my_input', 'red')
Just add this. It will inherit the color in input[type=text]:focus new color
.your-class ::placeholder{ color: inherit;}
Here is an example of dynamically setting pseudo-element styles using jQuery – it's a matter of creating a <style> element, setting its text content to the desired style declarations, and appending it to the document.
Here is a simple single-page example:
<!doctype html>
<html>
<head>
<title>Dynamic Pseudo-element Styles</title>
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<script>
$(document).ready(function() {
createStyles();
$('#slider-font-size').on('change', createStyles);
function createStyles() {
// remove previous styles
$('#ph-styles').remove();
// create a new <style> element, set its ID
var $style = $('<style>').attr('id', 'ph-styles');
// get the value of the font-size control
var fontSize = parseInt($('#slider-font-size').val(), 10);
// create the style string: it's the text node
// of our <style> element
$style.text(
'::placeholder { ' +
'font-family: "Times New Roman", serif;' +
'font-size: ' + fontSize + 'px;' +
'}');
// append it to the <head> of our document
$style.appendTo('head');
}
});
</script>
</head>
<body>
<form>
<!-- uses the ::placeholder pseudo-element style in modern Chrome/Firefox -->
<input type="text" placeholder="Placeholder text..."><br>
<!-- add a bit of dynamism: set the placeholder font size -->
<input id="slider-font-size" type="range" min="10" max="24">
</form>
</body>
</html>
I was using MaterializeCSS; I used Jquery to update CSS for input fields like this
$(".input-field").css("color", themeColor);
$(".input-field>.material-icons").css("color", themeColor);
$(".input-field>label").css("color", themeColor);
See Result:
https://codepen.io/hiteshsahu/pen/EXoPRq?editors=1000

Add style to part of text

Can I add style to part of text from an <input> value or a <span>?
I have some data like:
{text text} an other text...
And I will apply style for the text between {}.
My data is: <span>{RFS.KIS.ZWO} JJD000090085077412015021014193191</span>
I don't really see the js part here.
If I understood correctly you want CSS styles on a part of text. To do this you can put that text in an html tag and add a CSS class with the desired style to it. (changed formatting)
e.g.
HTML
<span class="myStyle">text text </span> more text.
CSS
.myStyle {
color: red;
}
For SPAN:
$(function() {
var text = $("span").text();
var replaced = text.replace(/\{(.*)\}/, function( $0, $1 ) {
return "{<span style='color: red;'>".concat($1, "</span>}");
});
$("span").html(replaced);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span>Text: {something}</span>
Wrap your text into tags instead of "{" "}"
calsses:
<span class="mytag">text text</span> text text
not you can style your class seperatly
<style>
.mytag {
color: blue;
}
</style>
or tags for example (not working for all browsers):
<mytag>text text</mytag> text text
not you can style your tag seperatly
<style>
mytag {
color: blue;
}
</style>

JQuery Find and change style of a string

I need to write a function that will search all the content in my HTML page for a specific string, and if it finds it then change the color of the text.
Is this possible?
Thanks
You could do that :
CSS :
.someclass {
color: red;
}
Javascript :
$('p:contains('+yourstring+')', document.body).each(function(){
$(this).html($(this).html().replace(
new RegExp(yourstring, 'g'), '<span class=someclass>'+yourstring+'</span>'
));
}​);​
Note that this would make problems if yourstring is in a tag or an attribute.
Demonstration
Be careful to run this code before you attach handlers to your paragraphs (or the elements inside which could contain yourstring, for example links).
The problem with dystroy's answer is that it will overwrite the entire HTML, so if you have any handlers within a node containing your text, they will be removed.
The correct solution is to use text ranges to update only the text itself, not all of the HTML around it. See Highlight text range using JavaScript
And for fun, there is a built-in method window.find that works in FF and Chrome. It's not in the standard though and will only find one at a time. Just like ctrl+f.
window.find("anything");
JQuery Find and change style of a string >> Only Copy Paste and run :)
$('#seabutton').click(function()
{
var sea=$('#search').val();
var cont=$('p').val();
alert(cont);
$('p:contains('+sea+')').each(function()
{
/* $(this).html($(this).html().replace(new RegExp(sea, 'g'),'<span class=someclass>'+sea+'</span>'));
*/ $(this).html($(this).html().replace(
new RegExp(sea, 'i'), '<span class=someclass>'+sea+'</span>'
));
});
});
$('p').click(function()
{
$(".someclass").css("color", "black");
});
$('#search').blur(function()
{
$(".someclass").css("color", "black");
});
})
</script>
<style type="text/css">
.someclass {
color: red;
}
</style>
</head>
<body>
<!-- Select Country:<select id="country" name="country">
</select>
<table id="state" border="1">
</table> -->
<br>
Enter Text:<input type="text" id="search"/><input type="button" id="seabutton" value="Search"/>
<div id="serach">
<p>This is ankush Dapke
</p>
</div>
</body>
</html>

How to bold label on click?

So the labels are populated from the database. Once the label is clicked, the label need to turn red and bold. when clicked on another label, the first label need to come back to original state and the new label should be activated and it needs to be bold and red. for some reason, the changeActiveStates() only works for the first 2 labels, i.e., when first label is clicked it turns red and when the second label is clicked the first label is turned black and the second label is turned red. when the third label is clicked, the second label remains red and the third one turns red. How do i fix this??
Here is the code:
<html>
<span>
<input type="hidden" name="LiabFilter" id= "idLib<%=liabkey %>" value="<%=liabkey %>" />
<div>
<label for="idLib<%=liabkey%>" id="liablabel" style="cursor: hand; padding-left: 25px; font-weight: normal"
onClick ="clearLiabFilter();
document.getElementById('idLib<%=liabkey%>').checked = true;
changeActiveStates(this);">
<%=liab.getName() %>
</br>
</label>
</div>
</span>
<style type="text/css">
.activate { font-weight: bold; color:#e40000;}
.visited{ font-weight: normal; color: #000000;}
</style>
<script>
function byId(id) {
return document.getElementById ? document.getElementById(id) : document.all[id];
}
var prevLink = "";
function changeActiveStates(ele) {
if (prevLink) byId(prevLink).className = '';
ele.className = 'activate';
prevLink = ele.id;
}
</script>
</html>
Are you averse to JQuery?
If not, this should work.
$('label').click(function() {
$('label').removeClass('activate'); /* Remove 'activate' class from all labels */
$(this).addClass('activate'); /* Add 'activate' class to clicked label
});
EDIT: Example on jsFiddle
EDIT: A little more detail as the questioner hasn't used JQuery before.
JQuery is a javscript library and so must be loaded by the browser before you can do all the nifty stuff.
Add the following between the <head></head> tags on your page:
<script src="http//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
(Why let google host JQuery for you?)
Then add the following, also between the tags but after the script tag given above:
$(document).ready(function() {
$('label').click(function() {
$('label').removeClass('activate'); /* Remove 'activate' class from all labels */
$(this).addClass('activate'); /* Add 'activate' class to clicked label
});
});
(What does $(document).ready() do?)
Maybe not the best of solutions, but have you considered using jQuery? It's generally not too much of a dependency , and will solve these sort of issues quite elegantly and easily for you. Plus. Cross-browser compatibility.

Categories

Resources