detecting a span while looping using jquery/js? - javascript

I wanted to detect a span element while looping through a div element i.e.
<div class="example">
These are some <span id ="special" class="anime">special</span> words
that should be faded in one after the other.
</div>
using javascript i split the words and fade them in one by one i.e.
JS:
function doSomething(spanID) {
alert(spanID);
}
var $el = $(".example:first"), text = $.trim($el.text()),
words = text.split(" "), html = "";
for (var i = 0; i < words.length; i++) {
html += "<span>" + words[i] + ((i+1) === words.length ? "" : " ") + "</span>";
};
$el.html(html).children().hide().each(function(i){
// if special span is detected
// get the span id pass it to doSomething function
$(this).delay(i*200).fadeIn(700);
});
$el.find("span").promise().done(function(){
$el.text(function(i, text){
return $.trim(text);
});
});
working example is here: http://jsfiddle.net/6czap/5/
everything works, it just that i need to detect any special spans so i can do something with them, and then the for loop should carry on doing what it deos. thanks

Try the following:
var orig = $(".example:first").html()
$el.html(html).children().hide().each(function(i){
$(this).delay(i*200).fadeIn(700);
}).promise().done(function(){
$('.example:first').html(orig);
});
demo!

Related

Using a javascript button to change html, with multiple values that are picked using an auto incrementing number

Basic html:
<button id="changer">Changer button</button>
<div id="text"> </div>
"Changer" is the button element in html, "text" is the div tag in which our text will be placed.
var selector = 0;
We set the selector to 0. Next, every time the button "changer" is clicked, we add 1 to the selector var, unless it has reached its max value of 14, in which case we start over. And based on the selector value, we pick from the available text values.
document.getElementById("Changer").onclick = function () {
if (selector < 14) {
selector++;
}
else {
selector = 0;
selector++;
}
document.getElementById("text").innerHTML = text;
}
if (selector = 1 ){
text = "<p>this is text 1</p>";
if (selector = 2 ){
text = "<p>this is text 2</p>";
etc...
The problem is, the function upon being clicked jumps right to the last text value available. How do I fix this? Will add live example soon if needed.
Your are assigning the selector inside the if condition to a value.
if(selector = 1) {...
What you actually want to do is check if the selectors value is equal to something like so:
if(selector == 1) {...
But you do not need to repeat the check, you can simply do:
var selector = 0;
var btn = document.getElementById('changer');
var output = document.getElementById('text');
btn.addEventListener('click', function() {
if (selector < 14) {
selector++;
output.innerHTML = "<p>this is text " + selector + "</p>";
} else {
selector = 0;
output.innerHTML = "";
}
})
<button id="changer">Changer button</button>
<div id="text"> </div>

Edit HTML list entry with javascript

Note: i searched a half hour. I need a special solution for this:
I have the folowing code already (node some Variables have german Names i hope that's ok)
function generateList () {
document.getElementById("liste").innerHTML =""
var listEasy = vorNameListe[i] + " " + nachNameListe[i] + " " + alterListe[i]
for (var i=0; i < vorNameListe.length; i++) {
document.getElementById("liste").innerHTML += "<li>" + listEasy + "</li>"
};
Now i need a javascript (pls no jquery) solution so the user can change every List entry by himself. How do i do that?
further explanation: The code i have is one to bring a "li" in a existing "ul" with every loop.
But then i want to give every "li entry" the ability to be changed by the user.
Are you trying to change text of every li of #liste ul?
function generateList() {
var liItems = document.querySelectorAll('#liste > li');
for (i = 0; i === liItems, i++) {
liItems[i].innerHTML = 'content';
}
}
i refined my edit function with jquery fdurther and further i will edit this entry for every step:
I have a Special Idea about an Edit function
https://stackoverflow.com/questions/28695711/edit-and-delete-selected-list-entrys

Regex join elements if directly next to each other

I have the following script which allows me to select text, and will then visually highlight it by wrapping the selected text in a span tag.
This normally works fine, but if there is a highlight tag separated from another highlight tag by only a space, it joins the two highlights together.
Javascript
var HVleftPanelContent = $("#highlight-view .top .content");
HVoutputUl = $("#highlight-view .contentBottom ul");
$("p").on("copy", highlight);
function highlight() {
var text = window.getSelection().toString();
var selection = window.getSelection().getRangeAt(0);
var selectedText = selection.extractContents();
var textStr = selectedText.textContent;
if (textStr == "\n") {
clearSelection();
return false;
} else if (textStr[textStr.length - 1] == "\n") {
textStr = textStr.slice(0, -1);
var reg = new RegExp("\n", "g");
textStr = textStr.replace(reg, "\n<b data='
'></b>") + "\n";
} else if (textStr.indexOf("\n") >= 0) {
var reg = new RegExp("\n", "g");
textStr = textStr.replace(reg, "\n<b data='
'></b>");
}
var span = $("<span class='highlight'>" + textStr + "</span>");
selection.insertNode(span[0]);
if (selectedText.childNodes[1] != undefined) {
$(selectedText.childNodes[1]).remove();
}
var txt = HVleftPanelContent.html();
HVleftPanelContent.html(txt.replace(/<\/span>(?:\s)*<span class="highlight">/g, ''));
HVoutputUl.html("");
$("#highlight-view .top .content .highlight").each(function () {
$("#highlight-view .contentBottom ul").append("<li><span>" + $(this).html() + "</span></li>");
});
saveIt();
clearSelection();
}
Recap
If HTML looks like this:
This is a short paragraph
And I highlight "is", the markup changes to:
This <span>is</span> a short paragraph
And then I highlight either "this" or "a", the markup erroneously changes to:
This <span>isa</short> paragraph
Instead of how it should change:
This <span>is</span> <span>a</span> paragraph
Potential Problem
I assume the problem lays in this line:
HVleftPanelContent.html(txt.replace(/<\/span>(?:\s)*<span class="highlight">/g, ''));
Where the Regex statement is joining <span> tags that are next to each other, which it should so that if two span tags are directly next to each other, it becomes one span, but the Regex isn't limiting the joining to only when they're directly next to each other.
So, basically, how can I change the Regex to only join span tags if they're directly next to each other.
Fairly simple, replace:
HVleftPanelContent.html(txt.replace(/<\/span>(?:\s)*<span class="highlight">/g, ''));
With:
HVleftPanelContent.html(txt.replace(/<\/span><span class="highlight">/g, ''));
The problem was (?:\s)*, which means match any white space 0 or more times, which means that it would match even the spans that are separated with spaces.

(jquery) change nested same html tag to other bbcode tag

ok here is what i have:
<div id="mydiv">
<font color="green"><font size="3"><font face="helvetica">hello world</font></font></font>
</div>
I know the tags are strange, but that's what produced by the website.
So basically I want to change the font tag to bbcdoe tag, the jquery code I wrote:
$("#mydiv").find("font").text(function(){
var text = $(this).text();
var size = $(this).attr("size");
var color = $(this).attr("color");
var face = $(this).attr("face");;
if(size!=undefined){
return '[size="'+size+'"]'+text+'[/size]';
}
if(color!=undefined){
return '[color="'+color+'"]'+text+'[/color]';
}
if(face!=undefined){
return '[type="'+face+'"]'+text+'[/type]';
}
});
so what I got is only: [color="green"] hello world [/color]. always only the first tag. any idea?
ps: I tried each, replaceWith, html(), all the same result. only the first tag is change.
The reason it doesn't work is because when you call
$("#mydiv").find("font").text("New text")
For each font tag, starting from the first tag, it will replace the text within that tag.
Here is an example to show you what's going on.
Example | Code
$fonts = $("font","#mydiv");
console.log($fonts.text());
$fonts.text(function(){
return "New text";
});
console.log($fonts.text());
Here is an example of how you could do it instead
Example | Code
jQuery.fn.reverse = [].reverse;
var attributes= ["size", "color", "face"];
var text = $.trim($("#mydiv").text());
$("font","#mydiv").reverse().each(function(i, e) {
for (var i = 0; i < attributes.length; ++i){
var attr = $(e).attr(attributes[i]);
if( typeof attr != "undefined")
text = "["+attributes[i]+"="+attr+"]"+text+"[/"+attributes[i]+"]";
}
});
$("#mydiv").text(text);
A room full of sad, wailing kittens wishes that you'd get rid of those <font> tags, but you could probably make it work by explicitly working your way down through the nested tags.
It does what it does now because the outer call to .text() runs for the very first <font> tag, and it obliterates the other tags.
edit — to clarify, when you call
$('#mydiv').find('font')
jQuery will find 3 font tags. The library will therefore call the function you passed into .text() for each of those elements. However, the first call will have the effect of removing the other two <font> elements from the DOM. Even though the library proceeds to call your callback for those elements, there's no effect because they're not on the page anymore.
Here's what could work:
var $fonts = $('#mydiv').find('font');
var text = $fonts.text();
var attrs = {};
$fonts.each(function(_, font) {
var names = ["size", "color", "face"];
for (var i = 0; i < names.length; ++i)
if (font[names[i]]) attrs[names[i]] = font[names[i]];
});
var newText = "";
for (var name in attrs) {
if (attrs.hasOwnProperty(name))
newText += '[' + name + '=' + attrs[name] + ']';
}
newText += text;
for (var name in attrs) {
if (attrs.hasOwnProperty(name))
newText += '[/' + name + ']';
}
$('#mydiv').text(newText);
Note that I'm not really sure why you want to put the BBCode onto the page like that, but it seems to be the intention.
Seems to me your first line should be:
$("#mydiv").find("font").each(function(){

Select words by js in search result

I am using jQuery and creating now search. And i want to change all words that match of search.
For example:
i type in textbox "hello world", Script get all words "hello" and "world" on page and replace it on "<b class="search_word">hello</b>" and "<b class="search_word">word</b>".
Is it possible?
PS.
Search in div but div contains many other html elements.
now i am using this:
if ($("#search_input").val() != "") {
var words = $("#search_input").val().split(/\s/g)
for (var i = 0; i < words.length; i++) {
var new_reg = new RegExp(words[i], 'gi');
var replaced = $(".content_area").html().replace(new_reg, "<b class='searched_word'>"+words[i]+"</b>")
$(".content_area").html(replaced);
}
}
it works but tags...
if i search something like: "b class is the best class in School" it destroy page structure
Ahh ok, I understand, "onpage" search... hm....
this is a copy from How do I select text nodes with jQuery?
var getTextNodesIn = (function() {
function textNodeFilter() {
return this.nodeType == 3;
}
return function(el) {
var $el = $(el);
return $el
.contents()
.filter(textNodeFilter)
.add(
$el
.find("*")
.contents()
.filter(textNodeFilter)
);
};
})();
you can now use
getTextNodesIn("body").each(function() {
var txt = $(this).text();
$(this).text(txt.replace(new RegExp(myWord,"g"), "<b>" + myWord + "</b>"));
});
Loop now through all of them and aply my filter previously written.
There where you found your word, you must select the whole text, and replace the found word with found Word

Categories

Resources