Jquery adding and removing elements dynamically - javascript

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

Related

how do you add inline styles in jquery?

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: ''})

text parsing then highlighting in textarea in javascript

Is there a neat way of highlighting texts in textarea on the fly while typing?
I would basically type in:
This is a [[note]] to do on friday.
on a textarea, then, using a highlighting library, I would call it in like this:
function FindAllNotes() {
var note = /^(?:\[{2}(?!\[+))(.+)(?:\]{2}(?!\[+))$/g
, input = ($(#textarea).val()).match(note);
$(#textarea).highlightWithinTextarea({
highlight: [input],
className: 'yellow'
});
}
$(#textarea).on('keyup', function () {
FindAllNotes();
});
But the problem is, everytime I type, it works and highlights notes enclosed in [[ ]], then I lose the cursor/focus on the textarea.
The plugin you linked to, can handle regular expression just as you want (although you should remove the ^ and $ from it, to not try to match the whole string).
$(function(){
$('.example').highlightWithinTextarea({
highlight: /(?:\[{2}(?!\[+))(.+)(?:\]{2}(?!\[+))/g,
className: 'highlight'
});
});
.example{
width:500px;
height:250px;
}
.highlight{
background-color:tomato;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://lonekorean.github.io/highlight-within-textarea/jquery.highlight-within-textarea.js"></script>
<link rel="stylesheet" href="http://lonekorean.github.io/highlight-within-textarea/jquery.highlight-within-textarea.css">
<textarea class="example">This is a [[note]] to do on friday.</textarea>
keep in mind that you need to include the css file from the plugin which wraps/aligns the textarea with the div text
You can use $("#textarea").focus(); to manually set the focus of a textbox. Maybe try calling this after your highlight function like the following:
$(#textarea).on('keyup', function () {
FindAllNotes();
$("#textarea").focus();
});

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.

jquery/javascript - how to "undo" a click event using if statement?

The below code takes into account different tags and turns the background red if the tag is clicked on. I want to code it so that if it is clicked on again, it changes back from red and 'deletes' the background, or at least set it to null. I have tried an if statement to no avail. I know that I can just make another click event that changes the background to white, but this is for experimental purposes and i was wondering if this CAN be done with if statements. thanks to ya.
<script>
$(document).ready(function() {
$("p, h1").click(function() {
$(this).css("background-color", "red");
if ($(this).css("background-color", "red")) {
$(this).css("background-color", "null");
}
});
});
</script>
First you need to use the getter version of .css() like
if($(this).css("background-color") == "red"){
but it still won't work because, the css getter will return a rgb format value and will return non consistent values across browsers.
So the solution is to use a css based solution using toggleClass()
.red {
background-color: red;
}
then
$(document).ready(function() {
$("p, h1").click(function() {
$(this).toggleClass("red");
});
});
Demo: Fiddle
$('p, h1').click(function() {
var $this = $(this);
var altColor = $this.data('altColor');
$this.css('background-color', altColor ? '' : 'red');
$this.data('altColor', ! altColor);
});
This answers your question, but you should really be using a CSS class for this.
This is easily done using CSS, and is a bit more straight forward. If you create a CSS class for the click, then you can just toggle it on/off each time the item is clicked:
CSS
p, h1 {
background-color: none;
}
p.red, p.h1 {
background-color: red;
}
JavaScript:
$('p, h1').click(function() {
$(this).toggleClass('red');
});

Apply CSS Repeatedly to Specific Words

I'm trying to apply CSS repeatedly and automatically to specific words.
For example, for the word "Twitter" I want the colour of the text to be #00ACED.
At present I am manually applying these colours around specific brand terms using span classes:
<span class="twitter">Twitter</span>
With the CSS:
.twitter {
color: #00ACED;
}
However, this is a process and I would prefer a method which completes this styling automatically. I have about 20 brand words with an associated colour styling.
Can anyone assist me with this problem. I am using WordPress if that makes any difference.
I think the most straight-forward way to do it is by using a smart jQuery highlight plugin I came across. After applying it, you'll be able to do what you're after. Below is an example, with a link to a live fiddle at the end:
HTML
<p>Some examples of how to highlight words with the jQuery Highlight plugin. First an example to demonstrate the default behavior and then others to demonstrate how to highlight the words Facebook and Twitter with their own class names. Words will be highlighted anywhere in the DOM, one needs only to be specific on where the script should look for the words. It supports case-sensitivity and other options, like in the case of YouTube.</p>
CSS
p { line-height: 30px; }
span { padding: 4px; }
.highlight { background-color: yellow; }
.facebook { background-color: #3c528f; color: white; }
.twitter { background-color: #1e9ae9; color: white; }
.youtube { background-color: #be0017; color: white; }
Highlight Plugin (needs to be loaded after jQuery and before the JavaScript below)
<script type="text/javascript" src="http://github.com/bartaz/sandbox.js/raw/master/jquery.highlight.js"></script>
JS
// default
$("body p").highlight("default");
// specify class name (not case sensitive)
$("body p").highlight("twitter", { className: 'twitter' });
$("body p").highlight("facebook", { className: 'facebook' });
// specify class name (case sensitive)
$("body p").highlight("YouTube", { className: 'youtube', caseSensitive: true });
Include this JavaScript at the bottom of the page (before the body closing tag so that you don't need to use the function below:
$(document).ready(function() {
// unnecessary if you load all your scripts at the bottom of your page
});
Fiddle for the win! :)
Something like this may work. You would have to loop through your search terms and this might not be the most effective way to do it.
function add_class (search, replacement) {
var all = document.getElementsByTagName("*");
for (var i=0, max=all.length; i < max; i++) {
var text = all[i].textContent || all[i].innerText;
if (text.indexOf(search) !== -1 && ! all[i].hasChildNodes()) {
all[i].className = all[i].className + " " + replacement;
}
}
}
var replacements = [
["Twitter","twitter"],
//
]
for (var i = replacements.length - 1; i >= 0; i--) {
add_class(replacements[i][0],replacements[i][1]);
};
Note: I didn't test this at all.
If you know minimum among of JavaScript, this JavaScript library can make your life much easier. it will convert all the letter in the string into a span tag. http://daverupert.com/2010/09/lettering-js/
For those of you interested in the answer, I've created a solution using WordPress functionality:
function replace_custom_word($text){
$replace = array(
'Twitter' => '<span class="twitter"><a title="Twitter" target="_blank" href="http://www.twitter.com/">Twitter</a></span>',
'Facebook' => '<span class="facebook"><a title="Facebook" target="_blank" href="http://www.facebook.com/">Facebook</a></span>'
);
$text = str_replace(array_keys($replace), $replace, $text);
return $text;}

Categories

Resources