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.
Related
I know plugins exist and already made ones as well, however, I want to make one on my own. I'm stuck though cuz I'm new to jQuery/JavaScript.
Right now no matter how many characters you type in, the entire page disappears instead of showing the words that have the characters I typed. What am I doing wrong?
<div class="searchOption">
<input type="text" id="search" placeholder="search">
</div>
<div class="searchFound">
<!--upon hitting enter, this div opens collapse. -->
</div>
/*Need to get the below search code working...*/
var thePage = $(".pageContainer");
$("#search").keyup(function(){
var input = $(this).val();
console.log(input);
//if match found, make corresponding div link appear in open collapsible div,
// else say nothing found in open collapsible div
thePage.each(function(index, value){
var foundText = $(this).text().toLowerCase();
$(value).toggle(foundText.indexOf(input) >= 0);
});
});
I know toggle will make things 'toggle' for lack of a better word, however, when I use closest or match, thePage does nothing.
I'm looking for some guidance in helping me build this. Thanks!
Can you clarify what you are trying to achieve? Maybe toss a simple test case up on a site like JSBin or CodePen?
You say the entire page disappears. It sounds like you expect the display of the page to be "filtered" down to elements that match the input. Are you sure the call to thePage.each() is behaving the way you want? You may want something like thePage.children() in the mix.
http://api.jquery.com/each/
http://api.jquery.com/children/
The specifics are gonna depend on the markup and corresponding DOM tree you're working with. But if you console.log() both index and value within your call to thePage.each() I think you'll see surprising results.
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.
I am still having trouble understanding regex. I am also not even sure if you can target a whole page...but without knowledge of how to format regex, its getting play with it.
I have a trademarked name that appears throughout my page. I'd like to use JS to add a (r) to the end of it every time it appears.
Can jquery/js accomplish this?
$("body").each(function() {
this.innerHTML = this.innerHTML.replace(
'breathe right',
'breathe right(r)');
});
Thanks!
This is a good use case for the CSS :after pseudo-element:
CSS
.product-name:after {
content: " \00AE"; /* add restricted symbol after every element with the product-name class */
}
HTML
<span class="product-name">My Product</span>
Working Demo
The easiest way is to wrap your product name in a span and tag it with a class. I'm not sure if that's less work that just adding the symbol to your markup to begin with, though.
The benefit of this approach is it would allow you to easily apply other styles to your product name, like bolding the text or changing the font color.
You can read more about the :after pseudo-element here.
Yes, but it won't be efficient if you tell jQuery to search the entire document. To make it efficient, you'll need to have jQuery get a specific location to search if you want any efficiency in it.
You don't need jQuery :
document.body.innerHTML = document.body.innerHTML.replace(/breathe right/g, 'breathe right(r)')
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
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