I have the following code:
var done = function(el) {
var tds = el.parent().parent().find('td');
for (var i in tds) {
tds[i].css('backgroundColor', 'green');
}
};
done($(this));
Where $(this) points to the element inside td tag - so I'm getting all nearby td tags and changing background color on them.
The problem is that it throws an error that tds[i].css function is undefined.
Doing this in clear javascript, with passing this, works perfectly, like so:
var done = function(el) {
var tds = el.parentNode.parentNode.getElementsByTagName('td');
for (var i in tds) {
tds[i].style.backgroundColor = 'green';
}
};
done(this);
What's wrong?
Maybe try this :
var done = function(el) {
var tds = el.parent().parent().find('td');
$(tds).each(function(){
this.css('backgroundColor', 'green');
});
};
done($(this));
Related
I want to pull into an array the classes of all of the <img> in a particular <div> and then use those classes to delete the first <img> that shares that class in a different <div>.
So far, I have this that calls the original array:
var class = $('.frame div img').each(function() {
return $(this).class;
}).get();
class.forEach(function(entry) {
console.log(entry);
});
The log outputs a list of the <img></img> lines.
After that, I get stuck.
//Iterate through array and delete first <img> in #grid that has the same class, limit one per iteration.
// var img_class = $.each(class, function(key, value) {
// console.log(value);
// return $(this).attr('class');
// });
$('#grid img').each(function(){
if($(this).attr('class') == img_class){
$(this).remove();
}
});
The goals are:
Getting an array of classes into the img_class variable
Delete only the first <img> as it iterates through each class in the array
Thanks!
I am not sure if I understood it right but would something like this be of any help?
var firstIDs = "";
$('.frame div img').each(function() {
firstIDs += $(this).attr('id') + ",";
});
var SplitIDs = firstIDs.split(",");
$('#grid img').each(function(){
for(var i = 0; i < SplitIDs.length; i++) {
if($(this).attr('id') == SplitIDs[i]){
$("#grid img #"+$(this).attr('id')+":first").remove();
}
}
});
I would suggest to use some other attribute than class, eg. 'data-type'.
With the collected attribute values (e.g. 'types' array) do:
var $grid = $('#grid');
// iterate over collected types
types.forEach(function(type)) {
// find within $grid the first <img> with data-type == type and remove it from DOM
$grid.find('img[data-type="' + type + '"]:eq(0)').remove();
}
You could also do all in one rush:
// iterate over source <img> set
$('.frame div img').each(function() {
// get current images type-attrib
var type = $(this).attr('data-type');
// find within $grid the first <img> with data-type == type and remove it from DOM
$grid.find('img[data-type="' + type + '"]:eq(0)').remove();
});
Try
$(function() {
var classes = $.map($(".frame div img"), function(v, k) {
return [$(v).attr("class")];
});
var d = [];
console.log($("#grid img").length);
$.each($("#grid img"), function(k, v) {
if ( classes.hasOwnProperty($(v).attr("class")) ) {
d.push(v); $("body").find($(d.slice(0, 1))).remove();
};
});
console.log($("#grid img").length);
});
jsfiddle http://jsfiddle.net/guest271314/yv95C/
When I click the button to insert bbcode to textarea The console alert : "Uncaught ReferenceError: myTextarea is not defined". Can you help me solve this problem ?
I have a code:
$(function(){
function formatText(el,tagstart,tagend){
var selectedText=document.selection?document.selection.createRange().text:el.value.substring(el.selectionStart,el.selectionEnd);// IE:Moz
var newText='['+tagstart+']'+selectedText+'[/'+tagend+']';
if(document.selection){//IE
el.focus();
var st=getCaret(el)+tagstart.length+2;
document.selection.createRange().text=newText;
var range=el.createTextRange();
range.collapse(true);
range.moveStart('character', st);
range.moveEnd('character',selectedText.length);
range.select();
el.focus();
}
else{//Moz
var st=el.selectionStart+tagstart.length+2;
var end=el.selectionEnd+tagstart.length+2;
el.value=el.value.substring(0,el.selectionStart)+newText+el.value.substring(el.selectionEnd,el.value.length);
el.focus();
el.setSelectionRange(st,end)
}
}
function getCaret(el) { // IE mission is tricky :)
el.focus();
var r = document.selection.createRange();
if (r == null) {
return 0;
}
var re = el.createTextRange(),
rc = re.duplicate();
re.moveToBookmark(r.getBookmark());
rc.setEndPoint('EndToStart', re);
var add_newlines = 0;
for (var i=0; i<rc.text.length; i++) {
if (rc.text.substr(i, 2) == '\r\n') {
add_newlines += 2;
i++;
}
}
return rc.text.length + add_newlines;
}
$("elements").after('<form action="/post" method="post" name="myForm"><textarea placeholder="Comments..." name="myTextarea"></textarea><span class = "repbbcode" title = "Bold" value="b" style="font-weight:bold" >B</span></form>');
$(".repbbcode").on("click" , function(){
formatText(myTextarea,'b','b');
});
});
$(".repbbcode").on("click" , function(){
formatText(myTextarea,'b','b');
^^^^^^^^^^
});
myTextarea is not defined. There is no
var myTextarea = ....
in your code. You need something like
$(".repbbcode").on("click" , function(){
var myTextarea = $("[name='myTextarea']).get(0);
formatText(myTextarea,'b','b');
});
You need to add var myTextarea = document.getElementsByName('myTextarea')[0];
$(".repbbcode").on("click" , function(){
var myTextarea = document.getElementsByName('myTextarea')[0]; // added myTextarea
formatText(myTextarea,'b','b');
});
In this line of code:
formatText(myTextarea,'b','b');
You have to pass as the first argument a DOM element. You can't just pass the name of a DOM element. It's easiest to use document.getElementById("myTextArea") and then set id="myTextArea" in your element.
So, your textarea HTML would be <textarea id="myTextArea" ...>.
And, your code would be:
var textareaElement = document.getElementById("myTextArea");
formatText(textareaElement,'b','b');
If you want to get the DOM element by name, you can do that too:
var textareaElement = document.getElementsByName("myTextArea")[0];
formatText(textareaElement,'b','b');
What is different here is that document.getElementsByName() returns a list of potentially multiple elements so you have to reach into that list with [0] to get the first item in the list to pass to your function.
There are many different ways to do this (using name, class, id, etc...). Usually if you are trying to get one unique element in a page, you would give it an id and use document.getElementById() or the jQuery equivalent.
I'm trying to build a "search in the shown elements" function with jquery and css.
Here's what I got so far:
http://jsfiddle.net/jonigiuro/wTjzc/
Now I need to add a little feature and I don't know where to start. Basically, when you write something in the search field, the corresponding letters should be highlighted in the list (see screenshot, the blue highlighted part)
Here's the script so far:
var FilterParticipants = function(options) {
this.options = options;
this.participantList = [];
this.init = function() {
var self = this;
//GENERATE PARTICIPANTS OPBJECT
for(var i = 0; i < this.options.participantBox.length ; i++) {
this.participantList.push({
element: this.options.participantBox.eq(i),
name: this.options.participantBox.eq(i).find('.name').text().toLowerCase()
})
}
//ADD EVENT LISTENER
this.options.searchField.on('keyup', function() {
self.filter($(this).val());
})
}
this.filter = function( string ) {
var list = this.participantList;
for(var i = 0 ; i < this.participantList.length; i++) {
var currentItem = list[i];
//COMPARE THE INPUT WITH THE PARTICIPANTS OBJECT (NAME)
if( currentItem.name.indexOf(string.toLowerCase()) == -1) {
currentItem.element.addClass('hidden');
} else {
currentItem.element.removeClass('hidden');
}
}
}
this.init();
}
var filterParticipants = new FilterParticipants({
searchField: $('#participants-field'),
participantBox: $('.single_participant'),
nameClass: 'name'
});
I think you're just complicating things too much... You can do this easily in a few lines. Hope this helps:
var $search = $('#participants-field');
var $names = $('.single_participant p');
$search.keyup(function(){
var match = RegExp(this.value, 'gi'); // case-insensitive
$names
.hide()
.filter(function(){ return match.test($(this).text()) })
.show()
.html(function(){
if (!$search.val()) return $(this).text();
return $(this).text().replace(match, '<span class="highlight">$&</span>');
});
});
I used hide and show because it feels snappier but you can use CSS3 animations and classes like you were doing.
Demo: http://jsfiddle.net/elclanrs/wTjzc/8/
Here`s the way to do it with jQuery autocomplete so question
If you want to build it on your own you can do the following:
1. Get the data of every item.
2. Make render function in which you will substitute say "Fir" in Fire word to Fire
3. Every time you change the text in the input you can go through the items and perform substitution.
I am using java-query to generate a chess board on page load:
Basically I have an empty body:
<body>
</body>
I then have the following javascript linked:
var addsquareblack=function(i,row){$(document).ready(function(){
var square=$('<div class="square"></div>');
if ((i%2)===0)
{square.css('background-color','brown');}
$('.row').last().append(square);
});};
var addsquarewhite=function(i,row){$(document).ready(function(){
var square=$('<div class="square"></div>');
if ((i%2)===0)
{square.css('background-color','white');}
else
{square.css('background-color','brown');}
$('.row').last().append(square);
});};
var create=function(a){$(document).ready(function(){
var row=$('<div class="row"></div>');
$('body').append(row);
if ((a%2)===0)
{for(var i=1;i<9;i++){addsquareblack(i,row);}}
else
{for(var i=1;i<9;i++){addsquarewhite(i,row);}}
});};
var addrows=function(){
for(var i=1;i<9;i++){create(i);}
};
I then call in a script in head:
<script> addrows() </script>
However, the addsquarewhite and addsquare black are not functioning properly: My divs with class row are being added to body correctly, but then all of the squares that I am adding are getting bunched into the very last div. I thought that they would get added only to the last div available at the time of the method call. Clearly I don't understand something about scope/flow in javascript. Please enlighten.
Thanks!
Also your usage on ready handler is wrong
It is because you are adding the square elements to the last row instead of the row.
$('.row').last().append(square)
instead
var addsquareblack=function(i,row){
var square=$('<div class="square">1</div>');
if ((i%2)===0) {
square.css('background-color','brown');
}
row.append(square);
};
var addsquarewhite=function(i,row){
var square=$('<div class="square">2</div>');
if ((i%2)===0) {
square.css('background-color','white');
} else {
square.css('background-color','brown');
}
row.append(square);
};
var create=function(a){
var row=$('<div class="row"></div>');
$('body').append(row);
if ((a%2)===0) {
for(var i=1;i<9;i++){
addsquareblack(i,row);
}
} else {
for(var i=1;i<9;i++){
addsquarewhite(i,row);
}
}
};
var addrows=function(){
for(var i=1;i<9;i++){
create(i);
}
};
$(document).ready(function(){
addrows();
});
Demo: Fiddle
I'm trying to modify this code to also give this div item an ID, however I have not found anything on google, and idName does not work. I read something about append, however it seems pretty complicated for a task that seems pretty simple, so is there an alternative? Thanks :)
g=document.createElement('div'); g.className='tclose'; g.v=0;
You should use the .setAttribute() method:
g = document.createElement('div');
g.setAttribute("id", "Div1");
You can use g.id = 'desiredId' from your example to set the id of the element you've created.
var g = document.createElement('div');
g.id = 'someId';
You can use Element.setAttribute
Examples:
g.setAttribute("id","yourId")
g.setAttribute("class","tclose")
Here's my function for doing this better:
function createElement(element, attribute, inner) {
if (typeof(element) === "undefined") {
return false;
}
if (typeof(inner) === "undefined") {
inner = "";
}
var el = document.createElement(element);
if (typeof(attribute) === 'object') {
for (var key in attribute) {
el.setAttribute(key, attribute[key]);
}
}
if (!Array.isArray(inner)) {
inner = [inner];
}
for (var k = 0; k < inner.length; k++) {
if (inner[k].tagName) {
el.appendChild(inner[k]);
} else {
el.appendChild(document.createTextNode(inner[k]));
}
}
return el;
}
Example 1:
createElement("div");
will return this:
<div></div>
Example 2:
createElement("a",{"href":"http://google.com","style":"color:#FFF;background:#333;"},"google");`
will return this:
google
Example 3:
var google = createElement("a",{"href":"http://google.com"},"google"),
youtube = createElement("a",{"href":"http://youtube.com"},"youtube"),
facebook = createElement("a",{"href":"http://facebook.com"},"facebook"),
links_conteiner = createElement("div",{"id":"links"},[google,youtube,facebook]);
will return this:
<div id="links">
google
youtube
facebook
</div>
You can create new elements and set attribute(s) and append child(s)
createElement("tag",{attr:val,attr:val},[element1,"some text",element2,element3,"or some text again :)"]);
There is no limit for attr or child element(s)
Why not do this with jQuery?
var newDiv= $('<div/>', { id: 'foo', class: 'tclose'})
var element = document.createElement('tagname');
element.className= "classname";
element.id= "id";
try this you want.
that is simple, just to make a new element with an id :
var myCreatedElement = document.createElement("div");
var myContainer = document.getElementById("container");
//setAttribute() is used to create attributes or change it:
myCreatedElement.setAttribute("id","myId");
//here you add the element you created using appendChild()
myContainer.appendChild(myCreatedElement);
that is all
I'm not sure if you are trying to set an ID so you can style it in CSS but if that's the case what you can also try:
var g = document.createElement('div');
g.className= "g";
and that will name your div so you can target it.
window.addEventListener('DOMContentLoaded', (event) => {
var g = document.createElement('div');
g.setAttribute("id", "google_translate_elementMobile");
document.querySelector('Selector will here').appendChild(g);
});