How can I show a hidden link in a jQuery table [duplicate] - html

I am trying to change the CSS using jQuery:
$(init);
function init() {
$("h1").css("backgroundColor", "yellow");
$("#myParagraph").css({"backgroundColor":"black","color":"white");
$(".bordered").css("border", "1px solid black");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="bordered">
<h1>Header</h1>
<p id="myParagraph">This is some paragraph text</p>
</div>
What am I missing here?

Ignore the people that are suggesting that the property name is the issue. The jQuery API documentation explicitly states that either notation is acceptable: http://api.jquery.com/css/
The actual problem is that you are missing a closing curly brace on this line:
$("#myParagraph").css({"backgroundColor":"black","color":"white");
Change it to this:
$("#myParagraph").css({"backgroundColor": "black", "color": "white"});
Here's a working demo: http://jsfiddle.net/YPYz8/
$(init);
function init() {
$("h1").css("backgroundColor", "yellow");
$("#myParagraph").css({ "backgroundColor": "black", "color": "white" });
$(".bordered").css("border", "1px solid black");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="bordered">
<h1>Header</h1>
<p id="myParagraph">This is some paragraph text</p>
</div>

You can do either:
$("h1").css("background-color", "yellow");
Or:
$("h1").css({backgroundColor: "yellow"});

To clear things up a little, since some of the answers are providing incorrect information:
The jQuery .css() method allows the use of either DOM or CSS notation in many cases. So, both backgroundColor and background-color will get the job done.
Additionally, when you call .css() with arguments you have two choices as to what the arguments can be. They can either be 2 comma separated strings representing a css property and its value, or it can be a Javascript object containing one or more key value pairs of CSS properties and values.
In conclusion the only thing wrong with your code is a missing }. The line should read:
$("#myParagraph").css({"backgroundColor":"black","color":"white"});
You cannot leave the curly brackets out, but you may leave the quotes out from around backgroundColor and color. If you use background-color you must put quotes around it because of the hyphen.
In general, it's a good habit to quote your Javascript objects, since problems can arise if you do not quote an existing keyword.
A final note is that about the jQuery .ready() method
$(handler);
is synonymous with:
$(document).ready(handler);
as well as with a third not recommended form.
This means that $(init) is completely correct, since init is the handler in that instance. So, init will be fired when the DOM is constructed.

The .css() method makes it super simple to find and set CSS properties and combined with other methods like .animate(), you can make some cool effects on your site.
In its simplest form, the .css() method can set a single CSS property for a particular set of matched elements. You just pass the property and value as strings and the element’s CSS properties are changed.
$('.example').css('background-color', 'red');
This would set the ‘background-color’ property to ‘red’ for any element that had the class of ‘example’.
But you aren’t limited to just changing one property at a time. Sure, you could add a bunch of identical jQuery objects, each changing just one property at a time, but this is making several, unnecessary calls to the DOM and is a lot of repeated code.
Instead, you can pass the .css() method a Javascript object that contains the properties and values as key/value pairs. This way, each property will then be set on the jQuery object all at once.
$('.example').css({
'background-color': 'red',
'border' : '1px solid red',
'color' : 'white',
'font-size': '32px',
'text-align' : 'center',
'display' : 'inline-block'
});
This will change all of these CSS properties on the ‘.example’ elements.

When you are using Multiple css property with jQuery then you must use the curly Brace in starting and in the end. You are missing the ending curly brace.
function init() {
$("h1").css("backgroundColor", "yellow");
$("#myParagraph").css({"background-color":"black","color":"white"});
$(".bordered").css("border", "1px solid black");
}
You can have a look at this jQuery CSS Selector tutorial.

If you have one css:
$("p").css("background-color": "pink");
If you have more than one css:
$("p").css({"background-color": "pink", "font-size": "200%"});
Or you can use:
var style ="background-color:red;";
$("p").attr("style", style);

Just wanted to add that when using numbers for values with the css method you have to add them outside the apostrophe and then add the CSS unit in apostrophes.
$('.block').css('width',50 + '%');
or
var $block = $('.block')
$block.css({ 'width': 50 + '%', 'height': 4 + 'em', 'background': '#FFDAB9' });

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$( document ).ready(function() {
$('h1').css('color','#3498db');
});
</script>
<style>
.wrapper{
height:450px;
background:#ededed;
text-align:center
}
</style>
</head>
<body>
<div class="wrapper">
<h1>Title</h1>
</div>
</body>
</html>

$(".radioValue").css({"background-color":"-webkit-linear-gradient(#e9e9e9,rgba(255, 255, 255, 0.43137254901960786),#e9e9e9)","color":"#454545", "padding": "8px"});

$(function(){
$('.bordered').css({
"border":"1px solid #EFEFEF",
"margin":"0 auto",
"width":"80%"
});
$('h1').css({
"margin-left":"10px"
});
$('#myParagraph').css({
"margin-left":"10px",
"font-family":"sans-serif"
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="bordered">
<h1>Header</h1>
<p id="myParagraph">This is some paragraph text</p>
</div>

wrong code:$("#myParagraph").css({"backgroundColor":"black","color":"white");
its missing "}" after white"
change it to this
$("#myParagraph").css({"background-color":"black","color":"white"});

Related

Make an action on class or id affect other

I am working with a Web Form (html) and a CSS file and I wanna know what do I need to write in the CSS to make an action on one class or id- affect an other class or id. For example: I have a
<p class="hh">
Hello!
</p>
(^^ this p tag's class is "hh")
And another one:
<p class="gb">
Goodbye!
</p>
(^^ this p tag's class is "gb")
I wanna write something in the CSS file so that whenever I click on whatever there is in the "hh" class, it will make something change in the "gb" class, so if I click on the text "Hello!" it will make the color of the text "Goodbye!" green. Please help me! I try to find out how to do it for a long long time...
Thank you!
This sounds more like you need a javascript solution. In general you are not really able to change something on a click event in CSS. Consider following solution:
const hh = document.getElementById("hh");
const gb = document.getElementById("gb");
hh.addEventListener("click", function() {
gb.style.color = "green";
});
gb.addEventListener("click", function() {
hh.style.color = "red";
});
<div id="hh">
Hello!
</div>
<div id="gb">
Goodbye!
</div>
A common practice for doing this is by using JavaScript, which is known as the programming language of the web. If you've never used JavaScript before it can be a little bit confusing but if you have experience in other general purpose programming languages such as Python or Java then it shouldn't take much time to pick up.
To do what you are asking, there are a few possible ways to do this. I will share what I believe to be the most simple although not the most robust. You can use JavaScript events to fire off certain functions when certain particular things happen to your elements. For example, you can modify your HTML like so:
<p class="hh" onclick="doSomething()">Hello!</p>
Then, either in a separate JavaScript file linked back to your html file or in the of your html file, you would define the doSomething() function:
function doSomething(){
document.getElementsByClassName("gb")...
}
The document.getElementsByClassName() function is one way to select HTML elements from a page and modify it via JavaScript, I suggest checking out the very good JavaScript tutorials on W3Schools for more and better ways to do this, but this is the general principal. You would then modify the HTML element any way you need to.
Hope this helps!
You need to do that using JavaScript. I have attached a example for that.
$(".one").on('click', function() {
$(".two").css('color', 'red');
})
.one{
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="one"> Change below text to RED </p>
<p class="two"> Black text </p>
There is a way to use a :focus state to change the look of parents, but it wouldn't be possible to differentiate between which click caused the parent to focus.
Here's a simple example using JavaScript and jQuery.
var helloEls = document.querySelectorAll('#jsTest .hh');
var goodbyeEls = document.querySelectorAll('#jsTest .gb');
helloEls.forEach(function(elem) {
elem.addEventListener("click", function() {
goodbyeEls.forEach(function(el) {
if (el.className==='gb active'){
el.className = 'gb';
} else {
el.className = 'gb active';
}
});
});
});
var gbEls = $('#jqueryTest .gb');
$('#jqueryTest .hh').click(function(){
if (gbEls.hasClass('active')){
gbEls.removeClass('active');
} else {
gbEls.addClass('active');
}
});
.gb.active {
color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="jsTest">
<p class="hh">
Hello!
</p>
<p class="gb">
Goodbye!
</p>
</div>
<div id="jqueryTest">
<p class="hh">
Hello!
</p>
<p class="gb">
Goodbye!
</p>
</div>

Coloring the text depending on numeric value using css

I want to color text based on its value, using css.
ie. if value is less than 20 --> red ,
if value is between 20 - 60 --> orange ,
if value is greater than 60 to 100--> green.
I don't want to add any class in the template depending on the value.
I found this Link: How do I change the background color with JavaScript? but it doesn't suffice as I have too many values to apply color to.
Also I want it to be more maintainable when adding new values in future.
It is not possible only with CSS.
You have to use JavaScript/jQuery to dynamically add the color, based on an object color match, and test if the value in the data-color HTML attribute is between the range for each element.
The JS code dynamically check if the element attribute is in a color range and apply the matched color.
If you will have to add some color and range in the future, simply add new values in the colorMatch hash, and update your CSS color class list.
##CSS
.red {color:red}
###HTML
<p data-color="19">Lorem 19</p>
###JS
var colorMatch = {
'0-19' : 'red',
'20-59' : 'orange',
'60-100' : 'green'
};
Here is the working fiddle
If you do not consider it cheating to not use the actual innerHTML as a condition, but rather construct it from a CSS variable using content you could do something like this (just as an effort to not use JS in this case):
<num style="--num:1"></num>
<num style="--num:99"></num>
<num style="--num:165"></num>
num {
--breakpoint: 100;
--g: calc((clamp(0, var(--num), var(--breakpoint)) - calc(var(--breakpoint) - 1)) * 255);
color: rgb(0, var(--g), 0);
}
num:after {
counter-reset: variable var(--num);
content: counter(variable);
}
In this scenario I am coloring any of the numbers green if they are above 100, but more rules can be added using the same method to serve your use-case.
With that said, I think there is probably no scenario where this would ever be useful, other than just technical trivia, as it is more readable to simply change the class of the element dynamically using plain JS. Still kinda fun way to use counter-reset and counter though.
Here is the same example on jsfiddle: https://jsfiddle.net/msz1aouc/24/
A simple approach could be
HTML
<div class="content">
<p>high</p>
</div>
<div class="content">
<p>low</p>
</div>
<div class="content">
<p>medium</p>
</div>
<div class="content">
<p>critical</p>
</div>
<div class="content">
<p>high</p>
</div>
Jquery
var content = $(".content p").text();
if (content == "high") {
$(this).css("color", "#ffffff");
}
if (content == "low") {
$(this).css("color", "#ccc");
}
if (content == "critical") {
$(this).css("color", "#000");
}

Character escaping in Polymer

I'm creating a component with Polymer which has a background image added with inline styles. The problem is that using double brackets inside parenthesis and quotes makes the {{imageurl}} act like a string. Any tips?
<div class="image-container" style="background-image: url( '{{imageurl}}' )">
Update: I've tried the method posted here with no luck.
What you will have to do is have a computed property that returns the style:
<div style$="{{divStyle}}">hi</div>
Note the use of $= here as were are data-binding to an attribute. See here for more info.
And your JavaScript:
Polymer({
is: "test-element",
properties: {
backgroundColor: {
type: String,
value: '#FF0000'
},
divStyle: {
computed: 'getDivStyle(backgroundColor)'
}
},
getDivStyle: function(backgroundColor) {
return 'background-color: ' + backgroundColor + ';';
}
});
See this plunker to see it in action.
String interpolation is not yet supported in Polymer 1.0. Use computed bindings instead.
<!-- Notice the `$` sign. Use attribute binding (`$=`) when binding native elements attribute -->
<div style$="{{_computeBackgroundImage(imageurl)}}"></div>
Polymer({
...
_computeBackgroundImage: function(url) {
return 'background-image: url('+url+');';
}
});

Can i use attributes of element to create style rules?

I'm noot good in english, so the title may seem a bit odd.
I want to use css function attr() like this:
I mean i have a container <div> and an inner <div> that i want to have width depending on data-width attribute. For example this would be great, but this doesnt work:
<div class="container">
<div data-width="70%">
</div
</div>
.container {
width: 600px;
height: 200px;
}
.container div {
width: attr(data-width);
height: 100%;
}
Is there any noJS way to use attributes like that?
UPDATE: Guys convinced me that the JS is the only way to do this :)
That's not a big problem (but that's bad. CSS, why youre so illogical? Is the difference between content:attr(data-width) and width: attr(data-width) so big ?).
One of the guys had an idea to go through the all elements with jQuery.
That's ok, but it is very... local? Don't know how to say it in english.
Anyway, i remaked his code a little bit and here it is:
allowed = ['width','color','float'];
$(document).ready(function () {
$('div').each(function (i, el) {
var data = $(el).data(),style = '';
if (!$.isEmptyObject(data)) {
$.each(data, function (attr, value) {
if (allowed.indexOf(attr) != - 1) {
style += attr + ': ' + value + '; ';
}
})
if (style.length != 0) {
$(el).attr('style', style);
}
}
})
})
Idea is simple:
1. We suppose that style we want to add to an element is the only one. I mean there are no scripts that will try to add some other styles,
2. We create an array of allowed attribute names, we need to avoid using wrong names at the style attribute, for example style="answerid: 30671428;",
3. We go through each element, save its data attributes in an object, check if object is empty, and if not - check every attribute if it is allowed, create a string that contains all styles that we need, and - finally - add our style string to the element as the content of style attribute.
That's all, thanks everybody
I would not advise to use CSS alone since it will not allow you to do what you're looking for... instead use a scripting language (in my case jQuery) to accomplish this functionality for you like so: jsFiddle
jQuery
jQuery(document).ready(function(){
var dataElem; // to store each data attribute we come accross
jQuery('div').each(function(){ //loop through each div (can be changed to a class preferably)
dataElem = jQuery(this); //get the current div
if(dataElem.data('width')){ //make sure it exists before anything further
dataElem.width(dataElem.data('width')); //set the element's width to the data attribute's value
dataElem.css("background-color", "yellow");
}
});
});
HTML
<p>The links with a data-width attribute gets a yellow background:</p>
<div>
w3schools.com
</div>
<div class="me" data-width="50"> <!-- change value to see the difference -->
disney.com
</div>
<div>
wikipedia.org
</div>
Notes on the above:
each, data, width.
Instead of doing data-width, use a class attribute. An html tag can have mutliple classes separated by spaces, so if you wanted to be very precise, you could set up as many classes as you need. For instance:
<div class="w70 h100">
</div>
Then in your css:
.w70{
width: 70%;
}
.h100{
height: 100%;
}
And so on.
Is there any noJS way to use attributes like that?
No, you cannot use CSS to set the width of the element to it's data-width attribute. CSS does not allow for this as attr() is only currently available for the CSS content property which is only available on css pseudo elements (::before and ::after).
How can you achieve this with as little javascript as possible?
This is extremely easy to do using the native host provided DOM API.
Select the elements using Document.querySelectorAll().
Iterate the elements and apply the styles using Element.style which can be retrieved from the data-width attribute using Element.dataset
(Demo)
var items = document.querySelectorAll('#container div'), item, i;
for(i = 0; (item = items[i]); i++) item.style.width = item.dataset.width;

Ideas for multicolored textbox?

In my site, I would like to implement a textbox where people can input a set of strings separated by a separator character.
For example the tags textbox at the bottom of this page: tags(strings) delimited by space(separator).
To make it more clear to the user, it would make a lot of sence to give each string a different background color or other visual hint.
I don't think this is possible with a regular input[text] control.
Do you deem it possible to create something like that with javascript? Has somebody done this before me already? Do you have any other suggestions?
Basic Steps
Put a textbox in a div and style it too hide it.
Make the div look like a text box.
In the onClick handler of the div, set the input focus to the hidden text box.
Handle the onKeyUp event of the hidden text box to capture text, format as necessary and alter the innerHtml of the div.
Tis quite straightforward. I'll leave you to write your formatter but basically you'd just splitString on separator as per the Semi-Working-Example.
Simple Outline
<html>
<head>
<script language="javascript" type="text/javascript">
function focusHiddenInput()
{
var txt = document.getElementById("txtHidden");
txt.focus();
}
function formatInputAndDumpToDiv()
{
alert('Up to you how to format');
}
</script>
</head>
<body>
<div onclick="focusHiddenInput();">
Some label here followed by a divved textbox:
<input id="txtHidden" style="width:0px;" onKeyPress="formatInputAndDumpToDiv()" type="text">
</div>
</body>
</html>
Semi-Working Example
You still need to extend the click handlers to account for tag deletion/editing/backspacing/etc via keyboard.... or you could just use a click event to pop up another context menu div. But with tags and spacer ids identified in the code below that should be pretty easy:
<html>
<head>
<script language="javascript" type="text/javascript">
var myTags=null;
function init()
{
document.getElementById("txtHidden").onkeyup= runFormatter;
}
function focusHiddenInput()
{
document.getElementById("txtHidden").focus();
}
function runFormatter()
{
var txt = document.getElementById("txtHidden");
var txtdiv = document.getElementById("txtBoxDiv");
txtdiv.innerHTML = "";
formatText(txt.value, txtdiv);
}
function formatText(tagText, divTextBox)
{
var tagString="";
var newTag;
var newSpace;
myTags = tagText.split(' ');
for(i=0;i<myTags.length;i++) {
newTag = document.createElement("span");
newTag.setAttribute("id", "tagId_" + i);
newTag.setAttribute("title", myTags[i]);
newTag.setAttribute("innerText", myTags[i]);
if ((i % 2)==0) {
newTag.style.backgroundColor='#eee999';
}
else
{
newTag.style.backgroundColor='#ccceee';
}
divTextBox.appendChild(newTag);
newTag.onclick = function(){tagClickedHandler(this);}
newSpace = document.createElement("span");
newSpace.setAttribute("id", "spId_" + i);
newSpace.setAttribute("innerText", " ");
divTextBox.appendChild(newSpace);
newSpace.onclick = function(){spaceClickedHandler(this);}
}
}
function tagClickedHandler(tag)
{
alert('You clicked a tag:' + tag.title);
}
function spaceClickedHandler(spacer)
{
alert('You clicked a spacer');
}
window.onload=init;
</script>
</head>
<body>
<div id="txtBoxDivContainer">
Enter tags below (Click and Type):<div id="txtBoxDiv" style="border: solid 1px #cccccc; height:20px;width:400px;" onclick="focusHiddenInput();"></div>
<input id="txtHidden" style="width:0px;" type="text">
</div>
</body>
</html>
Cursor
You could CSS the cursor using blink (check support) or otherwise just advance and hide as necessary an animated gif.
This is quite interesting. The short answer to your question is no. Not with the basic input element.
The real answer is: Maybe with some trickery with javascript.
Apparently Facebook does something close to this. When you write a new message to multiple persons in Facebook, you can type their names this sort of way. Each recognized new name is added a bit like an tag here and has an small cross next to it for removing it.
What they seem to do, is fake the input area size by drawing an input-looking box and removing all styling from the actual input with css. Then they have plenty of logic done with javascript so that if you have added an friend as a tag and start backspacing, it will remove the whole friends name at once. etc.
So, yes, it's doable, but takes plenty of effort and adds accessibility problems.
You can look how they do that at scripts like TinyMCE, which add such features to textareas. In textareas you can use HTML to colorize text.
You can use multiple textboxes
textbox1 <space> textbox2 <space> textbox3 ....
and so on... You can then apply the background-color style to each textbox.