how do you add inline styles in jquery? - javascript

Hi so this what I have in jquery however it doesn't seem to work, am I missing something?
modalClose.on("click", () => {
modalContainer.removeClass("modal-open");
modalContainer.attr("style", "display:none");
});

You use the css function, passing it an object with the properties, you use camel case rather than hyphens.
modalClose.on("click", () => {
modalContainer.removeClass("modal-open");
modalContainer.css({display: 'none'});
});
//Use camel case for properties with hyphens. style="display: none; background-color: #FFFFFF"
jQuery('.youritem').css({display: 'none', backgroundColor: '#FFFFFF'})
To remove a property from your html send an empty string to the property, the following removes both the display and background-color properties.
jQuery('.youritem').css({display: '', backgroundColor: ''})

Related

Difference between className and classList

Which one of the following should be preferred under what circumstances?
btnElement.classList.add('btn');
btnElement.className = 'btn';
Using "classList", you can add or remove a class without affecting any
others the element may have. But if you assign "className", it will
wipe out any existing classes while adding the new one (or if you
assign an empty string it will wipe out all of them).
Assigning "className" can be a convenience for cases where you are
certain no other classes will be used on the element, but I would
normally use the "classList" methods exclusively.
And "classList" also has handy "toggle" and "replace" methods.
https://teamtreehouse.com/community/difference-between-classlist-and-classname
ClassList as the name suggest is the list of classes in an element.
If you have multiple classes on an element and you want to add/remove one without altering the rest you should use classList.
classList also provides methods like toggle which are really useful.
function toggleClass(){
let txt = document.querySelector("h2");
txt.classList.toggle("changebg");
}
.font-style {
font-family: sans-serif;
}
.changebg {
background-color: lightcoral;
}
<h2 class="font-style" >Hello World!</h2>
<button onclick='toggleClass()'>Toggle Background Class</button>
Using "classList", you can add or remove a class without affecting any others the element may have. But if you assign "className", it will wipe out any existing classes while adding the new one (or if you assign an empty string it will wipe out all of them)
classList
Using classList, you can add or remove a class without affecting any other classes the element may have.
So this is helpful for adding additional classes to an element that contain other classes.
classList has some handy methods like toggle and replace.
if (clicked) {
button.classList.add('clicked');
} else {
button.classList.remove('clicked');
}
Here if the button was clicked it will add the clicked class along with other classes the element may have and it will remove only the clicked class from the element.
className
If you use className, it will wipe out any existing classes while adding the new one (or if you assign an empty string it will wipe out all of them).
Using className can be convenience when you know this element will not use any other classes.
if (clicked) {
button.className = 'clicked';
} else {
button.className = '';
}
In this case, className will wipe all the classes the element may have and add clicked class to it. The empty string('') will wipe all the classes.
Conclusion
the recommendation would be to use className whenever possible.
Use classList when you need classList methods like toggle, replace, etc.
context https://dev.to/microrony/difference-between-classlist-and-classname-45j7
You can see the changes in JavaScript to apply same difference one with use of classList and other with className .
It will be clear from 1st btn only that classList add extra name in class while className replaces the whole class (only .border is applied) .
Further are different function of classList which cannot be achieved by className and at last 4 line of code is reduced to 1 liner with use of toggle .
So you should look to your needs : Like, if you want to completely replace the class property names than use className else you can use classList property with different methods .add() .remove() .replace() .toggle() to only have changes in specific without hampering all names of class
Instruction for below snippet : Reload the snippet when you click one button so that clear differences can be seen on next btns
var classList1 = document.getElementById("part1")
var classname2 = document.getElementById("part2")
function funcAdd() {
classList1.classList.add("border");
classname2.className = "border";
}
function funcRemove() {
classList1.classList.remove("color");
classname2.style.color = "black";
}
function funcReplace() {
classList1.classList.replace("background", "background1");
classname2.style.backgroundColor = "lightgreen";
}
function funcToggle() {
classList1.classList.toggle("color1");
if (classname2.style.color == "gold") {
classname2.style.color = "blue";
} else {
classname2.style.color = "gold";
}
}
.background {
background-color: red
}
.background1 {
background-color: lightgreen
}
.color {
color: blue
}
.font {
font-size: 24px;
}
.border {
border: 10px solid black
}
.color1 {
color: gold;
}
<div id="part1" class="background color font">classList</div>
<br><br><br>
<div id="part2" class="background color font">className</div>
<br><br><br>
<button onclick="funcAdd()">Add a border class</button>
<button onclick="funcRemove()">Remove a color class</button>
<button onclick="funcReplace()">Replace a background class</button>
<button onclick="funcToggle()">Toggle a color class</button>
<br><br>
I have just known one thing difference between className and classList. className returns string within they are names of the current element and classList also returns names but as an array.

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! :)

Jquery adding and removing elements dynamically

I am trying to add and remove a span element dynamically. it's throwing syntax errors like
expected ')' and expected ';'
please help me to fix it.
<script type="text/javascript">
$(document).ready(function () {
$("input[data-required='true']").focus(function () {
$(this).css({ 'background-color': 'red' }).after("<span class="label_error;"style="color:red;font-size:10pt">This field is required</span>");
});
$("input[data-required='true']").blur(function () {
$(this).css({ 'background-color': 'white' }).remove("<span class="label_error;"style="color:red;font-size:10pt">This field is required</span>") ;
});
});
</script>
The way that you are concatenating the values in your HTML string is wrong,
.after("<span class='label_error' style='color:red;font-size:10pt;'>" +
"This field is required" +
"</span>");
To fix this issue either you can use single quote in your string wrapped by double quotes or try to escape the double quote by using \ like "avi\"s code is wrong".
On top of all, the best approach would be creating element by using jquery,
.after($("<span>", {class : 'label_error',
style : 'color:red;font-size:10pt;',
text : 'This field is required'
}));
This would be more readable and maintainable. And I forgot to spot another one error that you made in your code. You are using .remove() in a wrong way,
$("input[data-required='true']").blur(function () {
$(this).css({ 'background-color': 'white' }).next("span.label_error").remove();
});
You have to select the relevant element from your $(this) object and invoke remove over it.
And the best approach for finishing up your task is, allot the styling works to be done to the css by writing rules with relevant selectors (said by #rory)
input[data-required='true'] {
background-color: white;
}
input[data-required='true']:focus {
background-color: red;
}
span.label_error {
color: red;
font-size: 10pt;
}
And the js would be,
var errorMsg = $("<span>", {class: 'label_error',text: 'This field is required'});
$("input[data-required='true']").focus(function() {
$(this).after(errorMsg);
}).blur(function() {
$(this).next("span.label_error").remove();
});
DEMO
You have two issues. Firstly you need to use different quotes to delimit the string to those you use within the string. Helpfully, in JS you can use either single (') or double (") quotes to achieve the same purpose. Also, the class attribute should not have a trailing ;. It can be helpful to use a text editor which has syntax highlighting as it makes it nearly impossible to miss mistakes like that.
Your second problem is that the remove() method expects a selector, not a whole HTML string. To remove the span which was appended in the focus event, use next() to select it, then remove(). Try this:
$("input[data-required='true']").focus(function () {
$(this).css({ 'background-color': 'red' }).after('<span class="label_error" style="color: red; font-size: 10pt">This field is required</span>');
});
$("input[data-required='true']").blur(function () {
$(this).css({ 'background-color': 'white' }).next('span').remove();
});
Finally, note that it is much better practice to define your styles in CSS as it separates the HTML/JS from the styling rules, and helps make the JS shorter as well. Try this:
input[data-required='true'] {
background-color: white; /* transparent may work here too */
}
input[data-required='true']:focus {
background-color: red;
}
span.label_error {
color: red;
font-size: 10pt;
}
$("input[data-required='true']").focus(function () {
$(this).after('<span class="label_error">This field is required</span>');
}).blur(function () {
$(this).next('span').remove();
});
Working example

jQuery cannot assign to a function result

I am getting the error in the title above in the following code:
$j(".table").delegate('td','click', function(e) {
//alert($j(this).parent().css('background-color'));
if ($j(this).parent().css('background-color') == 'transparent')
$j(this).parent().css('background-color') = '#eee';
else {
$j(this).parent().css('background-color') = 'transparent';
}
});
I don't understand why I'd be getting this error, as I have made sure I am using the assignment operator == to compare the strings
There are 2 issues with your question: first one is already answered by #Mike Vranckx, the correct usage of .css() setter is passing a second argument to set as value.
The other problem is that your condition will never be true, I'll address it in this answer. If you fix it in the way I suggest, you won't be needing .css().
Computed CSS values, which are returned from getComputedStyle/jQuery's .css(), are not exactly what you've authored in your code -- they suffer transformations when parsed into the CSSOM.
For instance, in Chrome:
body { background-color: transparent; }
console.log( $('body').css('background-color') ); //returns "rgba(0, 0, 0, 0)"
See for yourself.
That's why your $(...).('background-color') == 'transparent' condition is always false.
The most clean and cross-browser solution is to apply styling with classes (.addClass(), removeClass(), toggleClass()) and do conditional checks with .hasClass().
In your case though, .toggleClass should suffice. Here's a simple way to write your logic (fiddle):
$j(".table").on('click', 'td', function() {
$j(this).parent().toggleClass('bg-gray');
});
.bg-gray {
background: #eee;
}
To set / change the background-color property, you need to pass it as a second argument:
$j(this).parent().css('background-color', '#eee');
While compare using background color better to use rgba like this
$j(this).parent().css('background-color', 'rgb(0,0,0)');
To assign value to css, pass the value as a second argument.
The below line will change to
$j(this).parent().css('background-color') = '#eee';
The following Line
$j(this).parent().css('background-color','#eee');
It would be cleaner, faster, and easier to modify to use a CSS class :
.table td { background-color: transparent; }
.foo { background-color: #EEE; }
And
$j( '.table' ).delegate( 'td', 'click', function() {
$( this ).toggleClass( 'foo' );
});
Also avoid using reserved words like "table" for class names, it's confusing.

ExtJS underlilning validation

For validation, I use a parameter
msgTarget: 'side'.
When you enter invalid data, underlining and an exclamation mark appear.
How to get rid of the underline?
The simplest way to achieve that is to override the base cls class of the element on its invalid behavior:
.x-form-invalid-field, textarea.x-form-invalid-field {
background-image: none;
}​
The most recommended way is to create a custom CSS class to do that same stuff, and apply that to the element (component) as a property:
.x-form-invalid-field-without-underline {
background-image: none;
}​
Ext.create('Ext.form.field.Text', {
... ,
invalidCls: 'x-form-invalid-field-without-underline'
});

Categories

Resources