I would like to replace abcName with xyzName?
<tr>
<td>
<b class="abcName">Bob</b>
</td>
</tr>
Using this, but on page load nothing changes:
var bobo = document.getElementsByTagName("td");
function user(a, b, c) {
try {
if (bobo[c].innerHTML.match('>' + a)) {
bobo[c].className = b;
}
} catch (e) {}
}
function customs() {
for (i = 0; i < bobo.length; i++) {
classChange("Bob", "xyzName", i);
}
}
setInterval("customs()", 1000);
Although I'm not real sure if what you're doing with the interval and whatnot is the best approach, you can:
var tidi = document.getElementsByTagName("td");
function changeStyleUser(a, b, c) {
try {
if (tidi[c].children[0].innerHTML.indexOf(a) === 0) {
tidi[c].className = b;
}
} catch (e) {}
}
function customizefields() {
for (i = 0; i < tidi.length; i++) {
changeStyleUser("Bob", "xyzName", i);
}
}
setInterval("customizefields()", 1000);
http://jsfiddle.net/zBmjb/
Note, you also had the wrong function name in your for loop as well.
If you use jQuery, this would be MUCH simpler.
EDIT
Using jQuery:
function customizefields(a) {
$('td b').each(function(){
if ($(this).text().indexOf(a) === 0) {
this.className = 'xyzName';
}
});
}
setInterval(function(){customizefields('Bob')}, 1000);
http://jsfiddle.net/zBmjb/1/
Also, note the use of the anonymous function instead of using a string in setInterval(). This allows you to not use eval(), which is considered expensive and potentially harmful.
EDIT 2
If you wanted to pass in a list of name and class associations, you could use an array with objects, like so:
function customizefields(arrNames) {
$('td b').each(function(){
for (var i = 0; i < arrNames.length; i++) {
if ($(this).text().indexOf(arrNames[i].name) === 0) {
this.className = arrNames[i].class;
}
}
});
}
var namesToChange = [
{'name':'Bob','class':'Bob'},
{'name':'Bert','class':'Bert'},
{'name':'Jeff','class':'Jeff'}
];
setInterval(function(){customizefields(namesToChange)}, 1000);
http://jsfiddle.net/zBmjb/4/
It feels messy though, since it searches for all selected nodes, then for each found, loops over the current node for each name looking for a matched value, all while doing this once a second. The cleaner approach would be to see if the name value from the current node was found:
function customizefields(objNames) {
$('td b').each(function(){
name = $(this).text();
if (name.indexOf(" ") != -1) {
name = name.substring(0, name.indexOf(" "));
}
if (objNames[name]) {
this.className = objNames[name];
}
});
}
var namesToChange = {
'Bob':'Bob',
'Bert':'Bert',
'Jeff':'Jeff'
};
setInterval(function(){customizefields(namesToChange)}, 1000);
http://jsfiddle.net/zBmjb/5/
EDIT 3
If you need multiple values, you can make the value for the object an object as well.
function customizefields(objNames) {
$('td b').each(function(){
name = $(this).text();
if (name.indexOf(" ") != -1) {
name = name.substring(0, name.indexOf(" "));
}
if (objNames[name]) {
this.className = objNames[name].class;
this.style.backgroundImage = "url(" + objNames[name].img + ")";
}
});
}
var namesToChange = {
'Bob':{'class':'Bob','img':'bobspic.jpg'},
'Bob':{'class':'Bert','img':'Bertphoto.jpg'},
'Bob':{'class':'Jeff','img':'jeff.jpg'}
};
setInterval(function(){customizefields(namesToChange)}, 1000);
Grab the element you want to change (can do this multiple ways, in this example i used ID).
var x = document.getElementById( 'id-of-my-element' );
x.className = 'b';
To remove a class use:
x.className = x.className.replace(/\bCLASSNAME\b/,'');
Hope this helps.
Change this line:
classChange("Bob", "xyzName", i);
to this:
changeStyleUser("Bob", "xyzName", i);
Your script will work fine then. Do yourself a favor and use a debugger. :-)
if (tidi[c].innerHTML.search("class=\"abcName\"")>=0) {
tidi[c].children[0].className = b;
}
Related
I have a JavaScript function that I want to fire once the user enters text inside an input element. Currently I can only see the function firing if I console.log it. How do I get it to fire using keyup method?
The relevant code is below.
var $ = function (selector) {
var elements = [],
i,
len,
cur_col,
element,
par,
fns;
if(selector.indexOf('#') > 0) {
selector = selector.split('#');
selector = '#' + selector[selector.length -1];
}
selector = selector.split(' ');
fns = {
id: function (sel) {
return document.getElementById(sel);
},
get : function(c_or_e, sel, par) {
var i = 0, len, arr = [], get_what = (c_or_e === 'class') ? "getElementsByClassName" : "getElementsByTagName";
if (par.length) {
while(par[I]) {
var temp = par[i++][get_what](sel);
Array.prototype.push.apply(arr, Array.prototype.slice.call(temp));
}
} else {
arr = par[get_what](sel);
}
return (arr.length === 1)? arr[0] : arr;
}
};
len = selector.length;
curr_col = document;
for ( i = 0; i < len; i++) {
element = selector[i];
par = curr_col;
if( element.indexOf('#') === 0) {
curr_col = fns.id(element.split('#'[1]));
} else if (element.indexOf('.') > -1) {
element = element.split('.');
if (element[0]) {
par = fns.get('elements', element[0], par);
for ( i =0; par[i]; i++) {
if(par[i].className.indexOf(element[1]> -1)) {
elements.push(par[i]);
}
}
curr_col = elements;
} else {
curr_col = fns.get('class', element[1], par);
}
} else {
curr_col = fns.get('elements', element, par);
}
}
return elements;
};
You need to bind your method to the keyup event on the page.
You could try
document.addEventListener('keyup', $)
Or assuming you have the input element as element you could do
element.addEventListener('keyup', $)
Your function will be passed the event which you could use to investigate the state of the element if you needed that information to trigger or not trigger things in the function.
Here's a quick sample where the function that get's run on keypress is changeColor.
var COLORS = ['red', 'blue','yellow', 'black']
var NCOLORS = COLORS.length;
function changeColor(ev) {
var div = document.getElementById('colored');
var colorIdx = parseInt(Math.random() * NCOLORS);
console.log(colorIdx);
var newColor = COLORS[colorIdx];
div.style.color = newColor
console.log("New color ", newColor)
}
document.body.addEventListener('keyup', changeColor)
Though I'm not using the event (ev), I like to show, in the code, that I expect that variable to be available.
See it in action here - http://codepen.io/bunnymatic/pen/yyLGXg
As a sidenote, you might be careful about calling your function $. Several frameworks (like jQuery) use that symbol and you may run into conflicts where you're overriding the global variable $ or where the framework overrides your version if it.
I'm trying to create a key mapping that keeps track of the frequency for each character of a string in my createArrayMap() function but I keep getting this error from firebug: TypeError: str.charAt(...) is not a function
I found the charAt() function on Mozilla's developer website it should be a function that exists.
var input;
var container;
var str;
var arrMapKey = [];
var arrMapValue = [];
function initDocElements() {
container = document.getElementById("container");
input = document.getElementById("inputbox");
}
function createArrayMap() {
str = input.value;
for (var i = 0; i < str.length; i++) {
if (arrMapKey.find(str.charAt(i)) == undefined) {
arrMapKey.push(str.charAt(i));
arrMapValue.push(1);
}
}
}
function keyPressHandler() {
createArrayMap();
console.log(arrMapKey);
console.log(arrMapValue);
}
function prepareEventHandlers() {
input.onfocus = function() {
if (this.value == "Start typing here!") {
this.value = "";
}
};
input.onblur = function() {
if (this.value == "") {
this.value = "Start typing here!";
}
};
input.onkeyup = keyPressHandler;
}
window.onload = function() {
initDocElements();
prepareEventHandlers();
};
The problem is not with String.charAt(), but with Array.find().
The first argument to find is a callback, but the result of str.charAt(i) is a character and not a callback function.
To search for an element in your array, you could use Array.indexOf() as #adeneo already suggested in a comment
function createArrayMap() {
var str = input.value;
for (var i = 0; i < str.length; i++) {
if (arrMapKey.indexOf(str.charAt(i)) == -1) {
arrMapKey.push(str.charAt(i));
arrMapValue.push(1);
}
}
}
See JSFiddle
You're not going about things in the most efficient manner... What if you changed it to look like this so you are continually updated with each keypress?
var keyMap = {};
...
input.onkeyup = keyPressHandler;
function keyPressHandler(e) {
var char = String.fromCharCode(e.keyCode);
if(!(char in keyMap))
keyMap[char] = 1;
else
keyMap[char]++;
}
This has been answered, but here's my version of your problem JSBIN LINK (also has an object option in addition to the array solution).
I moved some variables around so you'll have less global ones, added comments, and mocked with the output so it'll show it on the page instead of the console.
besides the Array.find() issues, you weren't initializing your arrays on the build method, and so, you would have probably ended with the wrong count of letters.
HTML:
<div id="container">
<textArea id="inputbox"></textArea></div>
<p id="output">output will show here</p>
JS:
var input, // Global variables
container, //
output; //
/**
* Initialize components
*/
function initDocElements() {
container = document.getElementById("container");
input = document.getElementById("inputbox");
output = document.getElementById("output");
}
/**
* Creates the letters frequency arrays.
* Note that every time you click a letter, this is done from scratch.
* Good side: no need to deal with "backspace"
* Bad side: efficiency. Didn't try this with huge texts, but you get the point ...
*/
function createArrayMap() {
var index, // obvious
tempChar, // temp vars for: char
tempStr = input.value, // string
len = tempStr.length, // for loop iteration
arrMapKey = [], // our keys
arrMapValue = []; // our values
for (var i = 0 ; i <len ; i++) {
// These 2 change each iteration
tempChar = tempStr.charAt(i);
index = arrMapKey.indexOf(tempChar);
// If key exists, increment value
if ( index > -1) {
arrMapValue[index]++;
}
// Otherwise, push to keys array, and push 1 to value array
else {
arrMapKey.push(tempChar);
arrMapValue.push(1);
}
}
// Some temp output added, instead of cluttering the console, to the
// a paragraph beneath the text area.
output.innerHTML = "array keys: "+arrMapKey.toString() +
"<br/>array values:"+arrMapValue.toString();
}
function keyPressHandler() {
createArrayMap();
}
function prepareEventHandlers() {
input.onfocus = function() {
if (this.value == "Start typing here!") {
this.value = "";
}
};
input.onblur = function() {
if (this.value === "") {
this.value = "Start typing here!";
}
};
input.onkeyup = keyPressHandler;
}
window.onload = function() {
initDocElements();
prepareEventHandlers();
};
BTW, as the comments suggest, doing this with an object will is much nicer and shorter, since all you care is if the object has the current char as a property:
/**
* Same as above method, using an object, instead of 2 arrays
*/
function createObject() {
var index, // obvious
tempChar, // temp vars for: char
tempStr = input.value, // string
len = tempStr.length, // for loop iteration
freqObj = {}; // our frequency object
for (var i = 0 ; i <len ; i++) {
tempChar = tempStr.charAt(i); // temp char value
if (freqObj.hasOwnProperty(tempChar))
freqObj[tempChar]++;
else
freqObj[tempChar] = 1;
}
}
I am using Typeahead by twitter. I am running into this warning from Intellij. This is causing the "window.location.href" for each link to be the last item in my list of items.
How can I fix my code?
Below is my code:
AutoSuggest.prototype.config = function () {
var me = this;
var comp, options;
var gotoUrl = "/{0}/{1}";
var imgurl = '<img src="/icon/{0}.gif"/>';
var target;
for (var i = 0; i < me.targets.length; i++) {
target = me.targets[i];
if ($("#" + target.inputId).length != 0) {
options = {
source: function (query, process) { // where to get the data
process(me.results);
},
// set max results to display
items: 10,
matcher: function (item) { // how to make sure the result select is correct/matching
// we check the query against the ticker then the company name
comp = me.map[item];
var symbol = comp.s.toLowerCase();
return (this.query.trim().toLowerCase() == symbol.substring(0, 1) ||
comp.c.toLowerCase().indexOf(this.query.trim().toLowerCase()) != -1);
},
highlighter: function (item) { // how to show the data
comp = me.map[item];
if (typeof comp === 'undefined') {
return "<span>No Match Found.</span>";
}
if (comp.t == 0) {
imgurl = comp.v;
} else if (comp.t == -1) {
imgurl = me.format(imgurl, "empty");
} else {
imgurl = me.format(imgurl, comp.t);
}
return "\n<span id='compVenue'>" + imgurl + "</span>" +
"\n<span id='compSymbol'><b>" + comp.s + "</b></span>" +
"\n<span id='compName'>" + comp.c + "</span>";
},
sorter: function (items) { // sort our results
if (items.length == 0) {
items.push(Object());
}
return items;
},
// the problem starts here when i start using target inside the functions
updater: function (item) { // what to do when item is selected
comp = me.map[item];
if (typeof comp === 'undefined') {
return this.query;
}
window.location.href = me.format(gotoUrl, comp.s, target.destination);
return item;
}
};
$("#" + target.inputId).typeahead(options);
// lastly, set up the functions for the buttons
$("#" + target.buttonId).click(function () {
window.location.href = me.format(gotoUrl, $("#" + target.inputId).val(), target.destination);
});
}
}
};
With #cdhowie's help, some more code:
i will update the updater and also the href for the click()
updater: (function (inner_target) { // what to do when item is selected
return function (item) {
comp = me.map[item];
if (typeof comp === 'undefined') {
return this.query;
}
window.location.href = me.format(gotoUrl, comp.s, inner_target.destination);
return item;
}}(target))};
I liked the paragraph Closures Inside Loops from Javascript Garden
It explains three ways of doing it.
The wrong way of using a closure inside a loop
for(var i = 0; i < 10; i++) {
setTimeout(function() {
console.log(i);
}, 1000);
}
Solution 1 with anonymous wrapper
for(var i = 0; i < 10; i++) {
(function(e) {
setTimeout(function() {
console.log(e);
}, 1000);
})(i);
}
Solution 2 - returning a function from a closure
for(var i = 0; i < 10; i++) {
setTimeout((function(e) {
return function() {
console.log(e);
}
})(i), 1000)
}
Solution 3, my favorite, where I think I finally understood bind - yaay! bind FTW!
for(var i = 0; i < 10; i++) {
setTimeout(console.log.bind(console, i), 1000);
}
I highly recommend Javascript garden - it showed me this and many more Javascript quirks (and made me like JS even more).
p.s. if your brain didn't melt you haven't had enough Javascript that day.
You need to nest two functions here, creating a new closure that captures the value of the variable (instead of the variable itself) at the moment the closure is created. You can do this using arguments to an immediately-invoked outer function. Replace this expression:
function (item) { // what to do when item is selected
comp = me.map[item];
if (typeof comp === 'undefined') {
return this.query;
}
window.location.href = me.format(gotoUrl, comp.s, target.destination);
return item;
}
With this:
(function (inner_target) {
return function (item) { // what to do when item is selected
comp = me.map[item];
if (typeof comp === 'undefined') {
return this.query;
}
window.location.href = me.format(gotoUrl, comp.s, inner_target.destination);
return item;
}
}(target))
Note that we pass target into the outer function, which becomes the argument inner_target, effectively capturing the value of target at the moment the outer function is called. The outer function returns an inner function, which uses inner_target instead of target, and inner_target will not change.
(Note that you can rename inner_target to target and you will be okay -- the closest target will be used, which would be the function parameter. However, having two variables with the same name in such a tight scope could be very confusing and so I have named them differently in my example so that you can see what's going on.)
In ecmascript 6 we have new opportunities.
The let statement declares a block scope local variable, optionally initializing it to a value.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let
Since the only scoping that JavaScript has is function scope, you can simply move the closure to an external function, outside of the scope you're in.
Just to clarify on #BogdanRuzhitskiy answer (as I couldn't figure out how to add the code in a comment), the idea with using let is to create a local variable inside the for block:
for(var i = 0; i < 10; i++) {
let captureI = i;
setTimeout(function() {
console.log(captureI);
}, 1000);
}
This will work in pretty much any modern browser except IE11.
var data = {};
data.event = [
{
"id":"998",
"title":"Foo",
"thumb":"",
"source":""
},
{
"id":"999",
"title":"Bar",
"thumb":"",
"source":""
}
]
Given that id=998 I need to extract the value of the "title" and I'm a bit lost as to the proper syntax.
You can iterate with $.each() and check to see if the ID matches, and then write the value of title to a variable.
var title;
$.each(data.event, function(i,e) {
if (this.id==='998') {
title=this.title;
return false;
}
});
FIDDLE
function titleFromId(id) {
for (var i = 0, l = data.event.length; i < l; i += 1) {
if (data.event[i].id === id) {
return data.event[i].title;
}
}
}
var title = titleFromId('998');
You need to loop over the event array. For each item, if item.id is the value you are looking for, then return item.title.
Something like the following:
function findTitleById(desiredId) {
var title, item;
for (var i = data.event.length - 1; i >= 0; i--){
item = data.event[i];
if (item.id === desiredId) {
title = item.title;
break;
}
}
return title;
}
There are more advanced ways to do this, but I would understand the above before attempting them.
You can use $.each() function:
$.each(data.event, function(i, v){
alert(v.id + " " + v.title)
})
http://jsfiddle.net/NGALP/
This question already has answers here:
How can I change an element's class with JavaScript?
(33 answers)
Closed 8 years ago.
Could anyone let me know how to remove a class on an element using JavaScript only?
Please do not give me an answer with jQuery as I can't use it, and I don't know anything about it.
The right and standard way to do it is using classList. It is now widely supported in the latest version of most modern browsers:
ELEMENT.classList.remove("CLASS_NAME");
remove.onclick = () => {
const el = document.querySelector('#el');
el.classList.remove("red");
}
.red {
background: red
}
<div id='el' class="red"> Test</div>
<button id='remove'>Remove Class</button>
Documentation: https://developer.mozilla.org/en/DOM/element.classList
document.getElementById("MyID").className =
document.getElementById("MyID").className.replace(/\bMyClass\b/,'');
where MyID is the ID of the element and MyClass is the name of the class you wish to remove.
UPDATE:
To support class names containing dash character, such as "My-Class", use
document.getElementById("MyID").className =
document.getElementById("MyID").className
.replace(new RegExp('(?:^|\\s)'+ 'My-Class' + '(?:\\s|$)'), ' ');
Here's a way to bake this functionality right into all DOM elements:
HTMLElement.prototype.removeClass = function(remove) {
var newClassName = "";
var i;
var classes = this.className.split(" ");
for(i = 0; i < classes.length; i++) {
if(classes[i] !== remove) {
newClassName += classes[i] + " ";
}
}
this.className = newClassName;
}
div.classList.add("foo");
div.classList.remove("foo");
More at https://developer.mozilla.org/en-US/docs/Web/API/element.classList
Try this:
function hasClass(ele, cls) {
return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}
function removeClass(ele, cls) {
if (hasClass(ele,cls)) {
var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
ele.className=ele.className.replace(reg,' ');
}
}
Edit
Okay, complete re-write.
It's been a while, I've learned a bit and the comments have helped.
Node.prototype.hasClass = function (className) {
if (this.classList) {
return this.classList.contains(className);
} else {
return (-1 < this.className.indexOf(className));
}
};
Node.prototype.addClass = function (className) {
if (this.classList) {
this.classList.add(className);
} else if (!this.hasClass(className)) {
var classes = this.className.split(" ");
classes.push(className);
this.className = classes.join(" ");
}
return this;
};
Node.prototype.removeClass = function (className) {
if (this.classList) {
this.classList.remove(className);
} else {
var classes = this.className.split(" ");
classes.splice(classes.indexOf(className), 1);
this.className = classes.join(" ");
}
return this;
};
Old Post
I was just working with something like this. Here's a solution I came up with...
// Some browsers don't have a native trim() function
if(!String.prototype.trim) {
Object.defineProperty(String.prototype,'trim', {
value: function() {
return this.replace(/^\s+|\s+$/g,'');
},
writable:false,
enumerable:false,
configurable:false
});
}
// addClass()
// first checks if the class name already exists, if not, it adds the class.
Object.defineProperty(Node.prototype,'addClass', {
value: function(c) {
if(this.className.indexOf(c)<0) {
this.className=this.className+=' '+c;
}
return this;
},
writable:false,
enumerable:false,
configurable:false
});
// removeClass()
// removes the class and cleans up the className value by changing double
// spacing to single spacing and trimming any leading or trailing spaces
Object.defineProperty(Node.prototype,'removeClass', {
value: function(c) {
this.className=this.className.replace(c,'').replace(' ',' ').trim();
return this;
},
writable:false,
enumerable:false,
configurable:false
});
Now you can call myElement.removeClass('myClass')
or chain it: myElement.removeClass("oldClass").addClass("newClass");
It's very simple, I think.
document.getElementById("whatever").classList.remove("className");
try:
function removeClassName(elem, name){
var remClass = elem.className;
var re = new RegExp('(^| )' + name + '( |$)');
remClass = remClass.replace(re, '$1');
remClass = remClass.replace(/ $/, '');
elem.className = remClass;
}
var element = document.getElementById('example_id');
var remove_class = 'example_class';
element.className = element.className.replace(' ' + remove_class, '').replace(remove_class, '');
I use this JS snippet code :
First of all, I reach all the classes then according to index of my target class, I set className = "".
Target = document.getElementsByClassName("yourClass")[1];
Target.className="";
document.getElementById("whatever").className += "classToKeep";
With the plus sign ('+') appending the class as opposed to overwriting any existing classes