Inserting smilies into div with jQuery - javascript

I'm working on some small chat application. I want to implement smilies over there so when i click on some smiley it will appear in textarea where user enters his message and when user clicks on select i want smilies to appear in div that contains the conversation.
After some workarounds i got to idea that replacing textarea with div contenteditable="true"
doesn't work that well so i did wrap certain smiley name with ':' like :wink: in textarea but still i need to replace :wink: with real span containing image as background.
Problem is i don't see a way to make this dynamically but doing each one by one.
for example:
if ($('.line:contains(":wink:")').length > 0) {
var oldLineHTML = $('.line:contains(":wink:")').html();
$('.line:contains(":wink:")').html(oldLineHTML.replace(/:wink:/gi, '<span class="wink></span>"'));
I have plenty of smilies so doing this very resource expensive function will costs me much and also will cause me lots of problems during maintenance.
How can i do that dynamically? Or maybe you have better solution which will require to re-design... I'm up to it if it is required.
thanks
}

var testString = "test1 :smile: test2 :wink:";
alert(testString.replace(/:([^:]*):/g, '<span class="$1"></span>'));

My suggestion is read every string that is wrapped by colons :[something]:, then convert it into span. So that you don't have to define every smile, and it is easy to maintain.

If you are doing this on page load, then you can do this in a $(document).ready(). Then you can use selector that you have $('.line:contains(":wink:")') and use the $each operator to loop over each one and perform the update. This will cover you for the page load. But if you refactor that $each code into a method, then you can call it each time the text is updated. I think this will give you the best in both cases. Something like this:
function replaceWinks(){
$('.line:contains(":wink:")').each(function(index) {
//Replace the wink here
});
}
$(document).ready(function(){
replaceWinks();
});
I would recommend replacing the winks server side for the page load though. It will be more performant. Also it will avoid content that changes when after the first view.

Jeaffrey Gilbert's idea is good, but I have another one that may be interesting:
write down you winks the way you want(let's say [SmileName]), and when processing the text with jquery, read every one of them, and replace the [ with <div class=" then replace the ] sign, with "></div>, this way, you will end up like this:
using these smilies:
1- [smile]
2- [wink]
3- [shy]
will lead to the following markup
1- <div class="smile"></div>
2- <div class="wink"></div>
3- <div class="shy"></div>
and using CSS, you will give every class of them, a different background image, which is the smile image.
by utilizing this method, every div will lead to displaying your smilies, and you will write the code once, and end up using it wherever you want, without repeating yourself

Related

how to avoid fetching a part of html page which is being called inside another page?

I am calling a .html page(say A.html, which is dynamically created by another software each time a request is made) inside another webpage (say B.html). I am doing this by using the .load() function. Everything works fine but the problem is I donot want the so many "br" tags (empty tags) present at the end of A.html into B.html. Is there any way to avoid fetching those "br" tags into B.html? Any suggestion would be of great help. Thank you in advance.
You can't avoid loading part of a file when you are just accessing it.
The best option would be to simply remove the extra <br> tags from the document to begin with. There is probably a better way to accomplish whatever they are attempting to accomplish.
With some server-side scripting, it could be possible to strip them automatically when you load it, but would probably be pretty bothersome to do.
Instead, if you can't remove the <br> elements for some reason, what might be easier, if you are just dealing with a handful of <br> tags would be to simply strip them out.
Since you mention using the load() function, I'm guessing you are using jQuery.
If that's the case, something like this would cleanly strip out any extra <br> tags from the end of the document.
Here is a JSfiddle which will do it: http://jsfiddle.net/dMJ2F/
var html = "<p>A</p><br><p>B</p><br><p>C</p><br><br /><br/>";
var $html = $('<div>').append(html);
var $br;
while (($br = $html.find('br:last-child')).length > 0) {
$br.remove();
}
$('p').text($html.html());
Basically, throw the loaded stuff in to a div (in memory), then loop through and remove each <br> at the end until there aren't any. You could use regex to do this as well, but it runs a few risks that this jQuery method doesn't.
You shout delete the br-tags in your A.html.
Substitute them by changing the class .sequence with marging-top:30px
And have an other value in your B.html-file.
You also can run this:
$('br', '.sequence').remove();​
in the load-function. It will strip all br-tags.
You can't avoid fetching a part of your page, but you CAN fetch only a part of it.
According to the jQuery docs, you can call load like this:
$("#result").load("urlorpage #form-id");
That way, you only load the form html inside the result element.

How can I select a block of text on a page, then move an element in front of it?

I have a div that will appear on the page at a separate point. It doesn't always appear on the page and can be added via a CMS if needed. There's a line of text that will appear within the body. If the user has decided to have this div added, it would need to be moved into position via jquery. So, I have this text:
<p><strong>Key Facts:</strong></p>
I want to find it using jquery, then move the other div in front of it. I tried a couple of different ways to select this text then move the div in front of it and haven't had any luck. The best way I found to find the text was to do this:
var foundin = $('*:contains("<p><strong>Key Facts:</strong></p>")');
From that point, to move the div into position, I thought I could something like this:
$('#DivIWantToMove').insertBefore($foundin);
That didn't work, though. I also looked at this:
$( $foundin ).before( $('#DivIWantToMove') );
AS you might imagine, since you're reading this, that didn't work either. So, I'm asking you, is it possible to do what I want? I'm fairly constrained by the CMS that we are using. The DIV I need to move will always be someplace on the page and I have to move it. The client doesn't want to have to add a class to <p><strong>Key Facts:</strong></p> so I'm let with this. If I could have a class on <p> then it would be super easy. I've already done it. The client doesn't like having an extra step. Any ideas?
I think contains selector only looks for text, not html tags. so you have to modify your contains selector. if your html is like this -
<div>
<p><strong>Key Facts:</strong>
</p>
</div>
<div id="move">something something</div>
and you want to move your <div id='move'> in front of p, then try this -
var foundin = $('p:contains("Key Facts")');
var divtomove = $('div#move');
foundin.before(divtomove);
Demo
Update also look into this QA: jQuery :contains with html. Instead of using contains you can use one of the methods from there.

Replacing to HTML Character Entities and reverting back

When replacing things in my chat room it comes up in the box as the 'HTML Character Entities'. However, I want it to revert back and actually show the character typed in when it is then shown in the chat room. So I am using the following code to stop any html from being entered and damaging the chat room by replacing certain html character with there entities (I want to get one or two working before I look at the others I know there are many more.) ....
Javascript
var str1 = this.value.replace(/>/g, '<');
if (str1!=this.value) this.value=str1;
var str2 = this.value.replace(/</g, '>');
if (str2!=this.value) this.value=str2;
and then the following code then displays the text after it has been entered into the database etc. and on updating the chat box it uses the following to add in the the updated messages ...
Returned from php and then displayed through the following javascript
$('#chatroomarea').append($("<p>"+ data.text[i] +"</p>"));
I have messed around with this a few times changing it to val and using
.html(.append($("<p>"+ data.text[i] +"</p>")));
Etc. But I have had no luck. I'm not quite sure how to do this I just need the HTML Character Entities to actually show up back in there true Character instead of displaying something such as... '&#62'
This might be something I need to actually put within the replacing code where it will include code of it's own on replacing such as (this is just an example I'm not exactly sure on how I would write it) ....
var str1 = this.value.replace(/>/g, '.html(<)');
Any help on this would be much appreciated, Thank you.
$('#chatroomarea').append($("<xmp>"+ data.text[i] +"</xmp>"));
HTML xmp tag
The use is deprecated, but supported in most browsers.
Another option will be to use a styled textarea , To my knowledge these two are the tags that doesn't bother rendering html tags as it is.

Get div from page

I've looked everywhere for a technique, but I failed to find much that suited my needs.
Basically, I would like to utilize JavaScript or jQuery (probably using Ajax) to grab a div that contains a word from a page on my site.
I'm not asking anyone to code this for me, I would just like to be pointed in the right direction.
For example, let's say I have this HTML page:
<div class='findfromthis'>hello guys</div>
<div class='findfromthis'>goodbye guys</div>
<div class='findfromthis'>goodbye people</div>
I would like to display all the divs that contain the word "guys" in them.
Thank you so much in advance!!
JQuery has a contains selector that will find all elements containing specific text. Something along the lines of $("div:contains('guys')") should do the trick. Then you can use .each or .show etc to work with the selected elements.
See http://api.jquery.com/contains-selector/ for more detail.
EDIT :
The following code was deemed useful by the OP. It'll select all divs with class "findfromthis" which don't contain the phrase "guys", and remove them from the DOM:
$("div.findfromthis:not(:contains('guys'))").remove();
Give your div a class, say '.myDiv' and then via jQuery:
$('.myDiv').doSomething...
I'm not entirely sure how AJAX would play into this, but to point you in the right direction:
http://api.jquery.com/jQuery.ajax/
Your edit is an entirely different question. But you'd do the same to get the divs. In this case, you'd use 'each':
$('.findfromthis').each(function(){
// for each div you can now grab the text it contains:
DivText = $(this).text();
// now you could use a variety of different JS seach techniques to find
// your content. But one example to search for a word or word fragment would be:
if (DivText.indexOf("guys") !== -1)){
// then this div has the word 'guys' in its text somewhere
}
})
If the search term is more complex (like not wanting to find fragments) then you may want to use REGEX for the search part instead.
Again, though, not sure where AJAX would fit into this. This all can happen client-side.

How to use onmouseover?

I have a list being displayed on a JSP. On mouse hover on any of the value i need to show a description corresponding that value. Need to show description not as an alert and also cannot make the values as hyperlink.
eg.
suppose the value is ABC so on mouse hover should show AppleBoyCat.
need to use onmouseover. let me know how to do it..
What do you want to do? If you just want to show a tooltip, you can set the title attribute of any element and it will be displayed as a tooltip.
Also, the abbr tag can be used as tooltips too:
<abbr title="test">stuff</abbr>
You can go about it in two ways:
1 - a hidden dom object (a div for instance) which reveals itself when you roll over whatever
or
2 - you can rewrite the html of the particular element you're mousing over.
You can load this data in when you load everything else (either as Javascript objects, or as markup, though that's much bulkier) or you can asynchronously load the description data from a service when you mouse over (though you'll have more lag).
jQuery is a quick and dirty way to achieve this (more quick than dirty), but straight JS or pretty much any other JS library will do as well.
Perhaps not the cleanest solution but something like this:
<a class='hover' rel='tooltip'>Link</a>
//Some hidden div, putting css inline just for example
<div id='tooltip' style='display:none;'>Content</div>
$(function() {
$('.hover').mouseover(function() {
var tooltip = $(this).attr('rel');
$('#' + tooltip).fadeIn();
});
});
And offcourse add a callback hiding it again. It just takes the value from rel of the link and use as an id for the div to show.
This is a quick and dirty solution, can be made alot smoother if you just work with it a little;)
There also alot of plugins out there allowing the same functionality in a cleaner fashion.
*Edit: Just noticed you added a comment on another post that you can't use jQuery.. shouldn't tag a post with something you're not intending to use.
As TJHeuvel already said, you can simply use the title attribute.
Best approach is to build the list with both the value and title attribute from within JSP, if not possible for some reason, you can build client side array of each value and its corresponding description then using JavaScript dynamically assign the title on mouseover.
Show us some more code to get more/better help.
For simple tooltips, the title attribute is most effective, as pointed out by TJHeuvel
If you need more advanced tooltips with HTML and CSS formatting, I'd suggest you use an external library.
One that works nicely without jQuery ist wz_tooltip download here, documentation here
When included correctly, you can add tooltips by calling the functions Tip() and UnTip() as follows:
Homepage

Categories

Resources