jQuery - change style of uncreated div elements - javascript

I was trying to searchengine for this, but I'm not sure how to call it exactly.
I can change the style of my div elements successfuly, for example:
$(document).ready($('div.element1').css("float", "left"));
This will successfully change all the elements of class element1 that exist. However, the new (after above is executed) elements will still spawn with old option of float: right;. What is my best/simplest option for permanently changing the style of this div? I can inject it manually after the element is created but that feels wrong to be honest.

It is better if you don't add inline style using .css() method, but instead just add/remove classes having your style, so create a class for all those elements' style.
If the newly created elements have the class you define, then they will have the style too.
Optionally, you can do this:
$(document).on('change or_other_event','your_selectors', function(){
// your code
});
If the new elements have classes element1, element2 ..., you would need something like this:
$(document).on('change','div[class*="element"]', function(){
// your code
});

Just create a new class on your css and then add that class to your new element
.newElement{
color:red//example style
}
$("<div>",{class:'newElement'})

Your code:
$(document).ready($('div.element1').css("float", "left"));
is equivalent to:
var element = $('div.element1').css("float", "left");
$(document).ready(element);
This means any un-drawn elements will not be affected. Instead use:
$(document).ready(function() {
$('div.element1').css("float", "left");
});
The above code ensures changes are made once the page has loaded.

Related

Swapping CSS with a Click addEventListener in JavaScript

I am having trouble getting a click event to work on a page. I have a Div with an ID of 'icon', and the class of 'lock', and I want to be able to click on this Div's background image to change the class from 'lock' to 'locked'.
Before any confusion happens, I have both classes in my external CSS file, and they add a background image to the Div. Also, I don't want to use JQuery, but addEventListener with a function. so far, this is what my JS looks like:
var elLock = document.getElementById('icon');
function changeLock(){
var imgSwitch = elLock.getAttribute('class');
if(imgSwitch !== 'unlock'){
elLock.className = 'unlock';
}else{
elLock.className('lock');
}
}
elLock.addEventListener('click', changeLock, false);
The desired result is what is in this youtube video: https://www.youtube.com/watch?v=oI2sRCN7CiM
Any help would be greatly appreciated. I would love to learn from mistakes i've made.
I would use the Element.classList property rather than what you're doing here ...
Then you could simply do:
elLock.addEventListener('click', function() {
elLock.classList.toggle('lock') },
false);
and leave unlock as a default class on the element. Every time you click on the element, it will toggle the lock class on-and-off, and you can use the cascading properties of CSS to override the background properties that are on your default unlock class.
Change an element's CSS with Javascript may provide some help, although it does reference to jQuery. Element.className could be what you need, or element.classList.
I'd check if the current class is 'unlock'. If one class is considered a default, the other class can toggle. Using CSS's cascading properties will allow the toggling class to override the default when it is present.
Alternatively you could remove the currently applied class and apply the other.
if (elLock.classList.contains('unlock')) {
elLock.classList.remove('unlock');
elLock.classList.add('lock');
}
else {
elLock.classList.remove('lock');
elLock.classList.add('unlock');
}

Creating a "selected item" javascript code for navigation menu?

I have a navigation menu with about 10 items, and I put together this code to update the links for which is selected and which is not. It manually updates classes. The problem is, as you can probably tell, its inefficient and its a pain to update. Is there a better way of doing it?
$('#Button1').click(function(){
$('#Button1').addClass("selectedItem");
$('#Button2').removeClass("selectedItem");
$('#Button3').removeClass("selectedItem");
$('#Button4').removeClass("selectedItem");
$('#Button5').removeClass("selectedItem");
$('#Button6').removeClass("selectedItem");
$('#Button7').removeClass("selectedItem");
$('#Button8').removeClass("selectedItem");
$('#Button9').removeClass("selectedItem");
$('#Button10').removeClass("selectedItem");
});
You could try something like this -
$("[id^='Button']").removeClass("selectedItem");
$('#Button1').addClass("selectedItem");
This will first remove all the selectedItem classes from any element which has an id attribute starting with "button". The second command then adds the class to Button1
You could also simply bind all the elements with the same handler like this -
var $buttons = $("[id^='Button']");
$buttons.on('click', function ()
{
$buttons.removeClass("selectedItem");
$(this).addClass("selectedItem");
});
For each element, when clicked, the class will be removed - the element that was clicked with then have the class added.
Checkout the Attribute Starts With Selector [name^="value"] selector.
I would suggest using classes because this is exactly what they are for - to denote groups of elements. While you can easily select your buttons using the method proposed by Lix (and you should use this method if you can't modify HTML), using class is a more unobtrusive:
var $buttons = $('.button').on('click', function() {
$buttons.removeClass('selectedItem');
$(this).addClass('selectedItem');
});
Meta example: http://jsfiddle.net/88JR2/
You could have a class .button and apply it to all your buttons then
$('#Button1').click(function(){
$('.button').removeClass("selectedItem");
$('#Button1').addClass("selectedItem");
});

Adding CSS styles to injected DOM elements

I am using javascript to inject a few DOM elements into the page. I am able to inject a single DOM element and apply CSS style to it:
var $e = $('<div id="header"></div>');
$('body').append($e);
$e.css({
background: '#fbf7f7',
});
Problem: If I have nested elements within $e, how can I apply CSS styles to the parents and its children seperately?
var $e = $('<div id="header"><div class="header-content"><span class="title"></span></div></div>');
As you have applied class to div inside parent element you can simply create a style to that class header-content and apply it.
In order to apply styles dynamically you can simply add class for individual elements like this
$('#id-of-element').addClass("header-content");
you can also find elements inside parent element like the one below
$e.find('.header-content').css('background-color', '#ccc');
Hi you can add css to any element using .css() method... Try the following example. I have added a div inside $e and applied different style... the thing is to use the id or class of the child inside parent div...
var $e = $('<div id="header"><div id="child"></div></div>');
$('body').append($e);
$e.css({
background: '#fbf7f7',
});
$('#child').css("background", "red");
To expand on my comments: if you need to access children regardless of any id or class, then just use $e.children().

Change CSS rule in class using JQuery

I have a class in CSS
.Foo
{
width:20px;
}
Using Jquery I would like to do something similar to this on an event:
$(".Foo").css("width", "40px");
This doesn't work. Is this the wrong approach? Should I use addClass() and removeClass()?
EDIT: I figured out my problem. This command does in fact work. In my particular application I hadn't created the elements using the class before I used the command, so when they were created nothing was changed.
Basically this command doesn't change the CSS style rule, just the elements using the class.
You can change a CSS style rule. You need to look at:
document.styleSheets collection
styleSheet.cssRules property (or styleSheet.rules for IE7 and IE8)
rule.selectorText property
rule.style property
For example:
var ss = document.styleSheets[0];
var rules = ss.cssRules || ss.rules;
var fooRule = null;
for (var i = 0; i < rules.length; i++)
{
var rule = rules[i];
if (/(^|,) *\.Foo *(,|$)/.test(rule.selectorText))
{
fooRule = rule;
break;
}
}
fooRule.style.width = "40px";
Working demo: jsfiddle.net/kdp5V
you could add the styling manually to the header with jquery:
$('head').append('<style id="addedCSS" type="text/css">.Foo {width:40px;}</style>');
then change it on an event like e.g. so:
$(window).resize(function(){
$('#addedCSS').text('.Foo {width:80px;}');
});
jQuery.css will find all existing elements on the page that have the Foo class, and then set their inline style width to 40px.
In other words, this doesn't create or change a css rule -- if you dynamically add an element with the Foo class, it would still have a width of 20px, because its inline style hasn't been set to override the default CSS rule.
Instead, you should use addClass and removeClass and control the styles in your static CSS.
Yes, you should use addClass and removeClass to change the styling. In your css, define a couple of different classes and switch between them.
You should be selecting an element with jQuery. You're aware that you aren't selecting the CSS class itself, correct?
Once you have an element with class="Foo", you can select it as you have, and either set css properties manually like you're trying to do, or you can use add class like so:
$(".Foo").addClass('Foo');
Granted of course, since you're selecting the same class that you're adding, it doesn't really make sense.
I got thsi example in CSS api help in JQuery API.
this worked for me : http://jsfiddle.net/LHwL2/
for complete help read the css api at http://api.jquery.com/css/
Try using multiple styles
.FooSmall
{
width:20px;
}
.FooBig
{
width:40px;
}
$('#theTarget').removeClass('FooSmall').addClass('FooBig');
This may work for you.
$(".Foo").css("width", "40px");

How do I assign custom classes to YUI3 plugin/widget objects

Consider the following code.
var overlay = new Y.Overlay({
id:'tooltip-tag',
bodyContent:"Loading.....",
xy:[e.target.getX(),e.target.getY()+30]
});
The overlay gets the id as given in attributes. But what if I want to add a class ?
IS there something like:
var overlay = new Y.Overlay({
**class:'tooltip-tag'**,
bodyContent:"Loading.....",
xy:[e.target.getX(),e.target.getY()+30]
});
No. Here are three ways to do what you want:
Add the class in your markup. I'm
guessing this isn't what you want.
Subclass Overlay and add a
className config attribute. If
you have other customization to do,
this is an attractive option.
Hook the overlay:render event and
attach the class there. Here's a
jsfiddle that demonstrates this
technique:
http://jsfiddle.net/4zN5M/1/

Categories