jQuery: equivalent of .live() for CSS? - javascript

How do I add CSS to elements that have been dynamically created?
Here is a simple example of what I would like to do:
$(document).ready(function() {
$('#container').html('<p id="hello">hello world</p>');
// The following line doesn't work.
$('#hello').css("background-color", "#FFF");
});
The reason I want to do this, and I can't think of another way of doing it, is that I want to use background colour on alternate rows of a table that is dynamically generated:
$("#results-table tr:even").css("background-color", "#FFF");
I need to use this line of jQuery specifically for IE8 and below, which don't support nth-child CSS selectors.

Actually, your code does work. You might want to check if you don't have multiple elements by that ID.
Edit:
Here's your code, without duplicate IDs: http://jsfiddle.net/FhTU7/
Final edit:
Your HTML background and element background are both white.

You could instead of directly setting the CSS also just add a class to the even rows
$("#results-table tr:even").addClass("alt");
CSS to set the row colours and then a different set of colours for the alternate rows
<style type="text/css">
tr
{
background: #fff;
color: #000;
}
tr.alt
{
background: #000;
color: #fff;
}
</style>

You could declare the new element as a variable...
$(document).ready(function() {
var $new = $('<p id="hello">hello world</p>');
$new.css({
backgroundColor: "#fff"
})
$('#container').append($new);
});
You could use appendTo...
$(document).ready(function() {
$('<p id="hello">hello world</p>').appendTo('#container').css({
backgroundColor: "#fff"
})
});
However, if you create the elements correctly then you can use the original CSS at the end...
$('#container').append('<p id="hello">hello world</p>');

Related

Can't change :hover CSS properties with JavaScript

Background:
I am building a Wordpress site with Elementor and will like to use Javascript to amend the hover properties.
What I have done:
Based on the answer in this solution (Change :hover CSS properties with JavaScript), I have been able to get my code to work in JSfiddle (https://jsfiddle.net/lindychen/hL60waqd/2/).
The problem:
However, when I import this code into my Wordpress site in the following manner, the code does not have any effect on my page. This is how I implement the code in Wordpress.
<script type="text/javascript">
if (localStorage.getItem('trackerxyz') === 'page_m') {
var css = 'button.elementor-button.elementor-size-sm:hover{ background-color: #cc3633; color: #ffffff } button.elementor-button.elementor-size-sm {background-color: rgba(204,54,51,0.86); #ffffff}';
var style = document.createElement('style');
if (style.styleSheet) {
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
document.getElementsByTagName('head')[0].appendChild(style);
}
</script>
Can someone please let me know how to resolve this? Thanks.
You can solve this just by this:
if (localStorage.getItem('trackerxyz') === 'page_m') {
var style = '<style>button.elementor-button.elementor-size-sm:hover{ background-color: #cc3633; color: #ffffff } button.elementor-button.elementor-size-sm {background-color: rgba(204,54,51,0.86); #ffffff}</style>';
document.head.insertAdjacentHTML('beforeend', style);
}
So no need to create nodes. See insertAdjacentHTML on MDN

jQueryUI animate(color) doesn't work

I want to animate background color of input element, but it doesn't works :(
JavaScript (when submit):
function sendImage() {
formularz = $('form#sendImage');
autor = formularz.children('input[name=autor]');
if (autor.val().length < 1 || autor.val().length > 20) {
console.log('start');
autor.animate({
backgroundColor: 'red',
width: '100px',
}, 3000, function() {
console.log('end');
});
}
}
jQuery liblaries:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<link rel="stylesheet" href="jquery-ui/jquery-ui.min.css">
<script src="jquery-ui/external/jquery/jquery.js"></script>
<script src="jquery-ui/jquery-ui.min.js"></script>
<!-- I tried also this -->
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
In JS function works well - logs in console are shown, width of element too is changing, but background color not and it do not show any errors in console.
Any suggestions?
jQuery cannot animate background colours by default. You have two options, first you could use a third party plugin. Secondly, you can use CSS. The latter is preferable. Here's how to do it by setting the transition CSS rule on the element and then just adding the class in your jQuery code.
input {
transition: all 3s;
}
input.error {
background-color: red;
}
function sendImage() {
var $formularz = $('form#sendImage');
var $autor = $formularz.children('input[name=autor]');
if ($autor.val().length < 1 || $autor.val().length > 20) {
$autor.addClass('error');
}
}
Working example
I am pretty sure in Javascript you need to indicate you are adding style to an element via its id. So if you set an element's Id to be autor it would work using the following in your if statement:
document.getElementById('autor').style.background-color="red";
Rory McCrossan, I tested your recommendations and 'backgroundColor' worked well, but later i wanted to check again the backgoundColor and it also works...
So I don't know what was wrong. Mayby some typo or I forgot about somethink.
Sorry for the confusion.

Remove div element on click jQuery not working

What I need :
I am trying to create tags on the click of a button. I was successful with my attempt to create divs on the click.
Problems :
As in all the websites one has seen, like in stack-overflow or when you write email addresses , as you finish writing the text a "tag" is formed with a "remove" button when you hover.
Now I want something like this, but I am confused in how to show that cross on the divs.
Also my problem is when I use elements, I am also giving some background color but that is static. And if the text grows then there is no background color on the part of the text.
How should I go about this problem ?
This is what I have tried so far : http://jsfiddle.net/abhighosh18/wk9uxfz5/1/
JS :
$('.btnAdd').on('click', function () {
$('<div/>', {
id: 'newCo',
title: $("#prodName").val(),
text: $("#prodName").val()
}).css({
fontWeight: 700,
width : '30px',
background : 'lightblue',
padding: '2px',
margin: '5px',
float : 'left'
}).appendTo("#content");
});
$('#newCo').on('click',function(){
$(this).remove();
});
Some illumination --
$('#newCo').on('click',function(){
$(this).remove();
});
The above won't work because the #newCo element does not exist at the time that line executes.
$(document).on('click','#newCo',function(){ $(this).remove(); });
This refactored line of code listens to the document and WILL work on elements that don't exist at the time the DOM is first loaded. However, ID is not what you want to use here... because IDs need to be unique and there would quickly be several div withs the same ID if you click the .btnAdd element.
There are many ways to accomplish what you want, I just wanted to illustrate why your approach is failing.
THE FIX: you could chain .addClass("removable-tag") within your div-creating click function (before .appendTo()), and listen to $(document).on('click','.removable-tag',function(){...});, and THAT would function as intended.
You can use display: inline-block css property and min-width instead of width:
$('.btnAdd').on('click', function () {
$('<div/>', {
id: 'newCo',
title: $("#prodName").val(),
text: $("#prodName").val()
}).css({
fontWeight: 700,
minWidth : '30px',
background : 'lightblue',
padding: '2px',
margin: '5px',
display: 'inline-block'
}).appendTo("#content");
});
http://jsfiddle.net/Lathtqd8/
NOTE: What follow is an answer to this part of question ( before update ) :
Now what I need is the CSS for the divs to be placed side-by-side. I
have seen the code for doing so, but I need to know how to write the
code for dynamically generated divs.
Another thing i tried was creating buttons instead of divs. That
placed my buttons side by side without any extra effort from CSS.
add this to your css :
#newCo {
float: left;
}
and remove the forcing width : '30px', from your JS code otherwise it will get broken on large content.
http://jsfiddle.net/tunecino/wk9uxfz5/5/
Add some class not id when you want to add multiple elements.
snippet added
--joy
//javascript
$('.btnAdd').on('click', function () {
$('<div/>', {
class: 'newCo',
title: $("#prodName").val(),
text: $("#prodName").val(),
'data-idn':'some_unique_number'
}).append('<a>x</a>')
.appendTo("#content")
.find('a').click(function(){
var idn = $(this).parent().data('idn');
$(this).parent().remove();
//removeCallback(idn); //call anything with idn if required
});
});
/*CSS*/
.newCo{float:left;min-width:30px;background:lightblue;font-weight:700;padding:2px;margin:5px;}
.newCo > a {cursor:pointer;margin:0 0 0 3px;border-radius:50%;color:red;padding:0;text-shadow:0px 0px 1px #fff;font-weight:200;font-size:16px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Product Name:<input id="prodName" type="text">
<button class="btnAdd" value="Click Me!">Add Product</button>
<br/><br/><br/><div id="content" height="100px" width="100px" style="color:blue"></div>
try this:
$("#mydiv").off('click');

change css of body on mouseover

I want to get an highlighting effect on some various div container while the rest of the site should be dampened down in opacity including the background-image.
Any idea?
Why does this code not work? tried .hover() instead of .mouseover() too but the function won't react on any input...
$(function () {
$('body').mouseover(function () {
$('body').prop({
"background-color": "red";
});
});
});
Another try would be to set a frame around the body tag in the html and then set props to that frame while the hovered frame is in normal state but I have no idea how to do this. Just beginning with js dev. :)
EDIT: did a fail...
$(function () {
$('body').mouseover(function () {
$('body').css({
"opacity": "0.3";
});
});
});
should be that way...
any way to apply the opacity to the background image too?!
fiddle Demo
Use .css()
Set one or more CSS properties for the set of matched elements.
$(function () {
$('body').mouseover(function () {
$(this).css({
"background-color": "red"
});
//or $(this).css("background-color","red");
});
});
this
.prop()
Set one or more properties for the set of matched elements.
.prop() will set the property for a particular element. In your case you have to use .css() to set the style. Please read .prop() and .css() to see the difference.
Try this,
$(function(){
$('body').mouseover(function(){
$(this).css({"background-color":"red"});
});
});
DEMO
Here's a FIDDLE
body {
background: gray;
min-height: 1000px; /* For demo purposes */
}
css
$(function() {
$('body').on('mouseover', function() {
$(this).css({ backgroundColor: 'red' });
});
});
animate
$(function() {
$('body').on('mouseover', function() {
$(this).animate({ backgroundColor: 'red' }, 600);
});
});
*Note: For some reason it doesn't work with jQuery 1.x(edge).
I think this is what you might want: a "dim" DIV element that adds a semi transparent black box on the entire page, that puts itself "below" the DIV you want to highlight, and then some javascript to turn it off and on, and rearrange the z indexes. The HTML would look something like this:
this is some text
<div id="div1" class="dimmable">hello</div>
<div id="div2" class="dimmable">goodbye</div>
<div id="dim"></div>
And then the JS:
$('div.dimmable').hover(function() {
$(this).css('z-index', 101);
$('#dim')
.css('z-index', 100)
.width($(window).innerWidth())
.height($(window).innerHeight())
.fadeIn();
}, function() {
var dimmable = $(this);
$('#dim').fadeOut({complete: function() {
dimmable.css('z-index', 99);
}});
});
You can see it working here.
A slight catch: the DIVs need to have position:relative, otherwise you can't change their z-indexes and you can't put them on top of the "dim" DIV. Also, anything with a higher z-index will not stay behind the "dim", of course, but you can just use higher numbers as a workaround.

how to remove the borders in JQuery Layout?

Hello I am using jquery layout plugin from http://layout.jquery-dev.net/ .
my options are following:
<script>
$(document).ready(function(){
// create page layout
pageLayout = $('body').layout(
{applyDemoStyles: true,
spacing_open:0,
spacing_closed: 0,
slidable: false,
togglerLength_closed: 0
});
pageLayout.panes.north.css('backgroundColor','#A6f');
// we need to remove the borders as well....
});
</script>
This removes sliders but:
How to remove the pane borders as well?
thanks Arman.
Remove one border:
pageLayout.panes.north.css('border','none');
Remove all borders:
As you should be quite sure that each pageLayout.pane will have o as a property:
for(property in pageLayout.panes){
pageLayout.panes[property].css('border', 'none');
}
How you should really do it - checks to make sure o is a property of pageLayout.pane before attempting to access it:
for(property in pageLayout.panes){
if(pageLayout.panes.hasOwnProperty(property)){
pageLayout.panes[property].css('border', 'none');
}
}
I haven't tried this plugin yet but since your last line is pretty much like the usual css try this.
pageLayout.panes.north.css({'backgroundColor' : '#A6f', 'border' : 'none'});
Using a css rewriting. After including the css layout file in the head section (usually jquery.ui.layout.css) you could add a style that rewrites the original.
<style>
.ui-layout-pane {
background: #FFF;
border: 0 none; //This rewrites the original style
padding: 10px;
overflow: auto;
}
</style>

Categories

Resources