I have been struggling with this for a few days. I need somebody to steer me in the right direction. I have been searching on the web. I am not sure if I took the right approach. What I need is that each time a person hovers over a particular keyword, it should display an alert box. In this example the word is else. When I run the code it does not give any errors and does not display anything when mouse hovers on the word.
function on_func2()
{
var searchString = 'else';
var elements = document.getElementById('paragraph2');
for (var i = 0; i < elements.length; i++)
{
if (elements[i].innerHTML.indexOf(searchString) !== -1)
{
alert('Match');
break;
}
}
}
I would do something like this:
It will go through and find all else words, and wrap them in a span with a listener bound:
<p id="hello">What else would you say?</p>
-
var hello = document.getElementById('hello');
var str = hello.innerHTML;
str = str.replace( /\b(else)\b/g, '<span onmouseover="func1()">$1</span>' );
hello.innerHTML = str;
function func1() {
alert('there');
}
Check out the fiddle.
Using jQuery lettering plugin
<p class="word_split">if you were not there, else I would not have won.<p>
$(".word_split").lettering('words');
$('.word_split').mouseover(function(event) {
var word=event.target.innerHTML;
if (word == "else")
alert("Yep");
});
here's a demo: jsFiddle
Related
I am trying to use a code that recognizes a text in a class and choose the correct button to click. Now I'm trying to use the number of characters in the class, but it did not work. Some tips?
window.onload=function(){ setInterval(autoPickOther, 2500); };
function autoPickOther(){
if(document.getElementsByClassName("text class").length<66){
document.getElementsByClassName("pickother")[0].click();
}
else{setInterval(autoClick,1200);}
}
function autoClick(){
if(document.getElementsByClassName("class 1").length>0){
document.getElementsByClassName("go")[0].click();
}
}
Ok guys I've made it! Probably not the best solution but I use the text length to filter the right answer like I've thought before. The problem was that I was not extracting the text from the class so following the example the new code would be something like this:
var readclass = document.getElementsByClassName("luck");
for (var i = 0; i < readclass.length; i++) {
var text = readclass[i].innerText;
}
var textlength = text.length;
window.onload=function(){
setInterval(autoPickOther, 1000); };
function autoPickOther(){
if(textlength < 20){ //Change number according to the number of characters in the sentence that you want to test
document.getElementsByClassName("pickother")[0].click();
}
else{setInterval(autoThanks,1000);}
}
I am working client side on a web page that I am unable to edit.
I want to use JS to click on a particular button, but it does not have a unique identifier.
I do know the class and I do know a (unique) string in the innerHTML that I can match with, so I am iterating through the (varying number) of buttons with a while loop looking for the string:
var theResult = '';
var buttonNum = 0;
var searchString = '720p';
while (theResult.indexOf(searchString) == -1
{
theResult = eval(\"document.getElementsByClassName('streamButton')[\" + buttonNum + \"].innerHTML\");
buttonNum++;
}
Now I should know the correct position in the array of buttons (buttonNum-1, I think), but how do I reference this? I have tried:
eval(\"document.getElementsByClassName('streamButton')[\" + buttonNum-1 + \"].click()")
and variation on the position of ()'s in the eval, but I can't get it to work.
You could try something like:
var searchStr = '720p',
// Grab all buttons that have the class 'streambutton'.
buttons = Array.prototype.slice.call(document.querySelectorAll('button.streamButton')),
// Filter all the buttons and select the first one that has the sreachStr in its innerHTML.
buttonToClick = buttons.filter(function( button ) {
return button.innerHTML.indexOf(searchStr) !== -1;
})[0];
You don't need the eval, but you can check all the buttons one by one and just click the button immediately when you find it so you don't have to find it again.
It is not as elegant as what #Shilly suggested, but probably more easily understood if you are new to javascript.
var searchString = '720p';
var buttons = document.getElementsByClassName("streamButton"); // find all streamButtons
if(buttons)
{
// Search all streamButtons until you find the right one
for(var i = 0; i < buttons.length; i++)
{
var button = buttons[i];
var buttonInnerHtml = button.innerHTML;
if (buttonInnerHtml.indexOf(searchString) != -1) {
button.click();
break;
}
}
}
function allOtherClick() {
console.log("Wrong button clicked");
}
function correctButtonClick() {
console.log("Right button clicked");
}
<button class='streamButton' onclick='allOtherClick()'>10</button>
<button class='streamButton' onclick='allOtherClick()'>30</button>
<button class='streamButton' onclick='correctButtonClick()'>720p</button>
<button class='streamButton' onclick='allOtherClick()'>abcd</button>
I would stay clear of eval here, what if the text on the button is some malicious javaScript?
Can you use jQuery? if so, check out contains. You can use it like so:
$(".streamButton:contains('720p')")
I'm looking for a way to capture the specific character (or character index in text) after the user clicks on it inside of a contenteditable div. Just to provide an example, please consider the following HTML:
<div contenteditable="true">
Hello world
</div>
Suppose the user clicks right between "o" and "r", is there a way to know that, using JavaScript?
I'd imagine this would be covered by the Selection API but all my inquiry so far has produced me nothing.
I appreciate any help that you can give me.
You can see the caret position, i have done a small snippet for you here. Have a look at it.
enter code herehttp://codepen.io/19sthil80/pen/pEooVR
You can always do something like this. Codepen Link
I have put an alert in so that you can see that it does indeed know what you clicked and if you click a space as in between Hello and World it knows as well.
var div = document.getElementById("div");
function clickify (e) {
var arr = (typeof e.innerText !== 'undefined') ? e.innerText.split("") : e.textContent.split(""),
max = arr.length,
i = 0,
template = "$c",
result = "";
for (; i < max; i += 1) {
result += template.replace("$c", arr[i]);
}
e.innerHTML = result;
}
clickify(div);
Firstly, I've made a CODEPEN or jsfiddles
Background:
Ok I have a span tag within a few header tags h1,h2,h3. Inside that spantag is the word
experience which is spelled backwards like so:
<h3>for <span class="hover-spell">ecneirepxe</span>.</h3>
Question
I'm unsure on the best way to approch this but I would like on hover:
reorder to spell experience correctly
if possible animate them overlapping another while re-ordering
I have no idea how to do this but I keep thinking regex, with arrays but this feels overly complicated and I really don't know anything about regex and proper array sorting. Any information to lead me in the right direction would be most appreciated. Or an edit to the codepen or jsfiddles would be so excellent.
One possible solution is to use css to accomplish this. This solution doesn't animate the transition, it just changes the order of the letters. Add this to your css:
.hover-spell:hover{
direction: rtl;
unicode-bidi: bidi-override;
}
Edit: Thanks to Marcel Gwerder for pointing out that it's not possible to animate the direction property
I found this answer, in another post (it goes through a given string of text and wraps each character in a span then assigns transiton styles to each), that may help with a jquery solution.
I've just tried to set up something animated with jquery, it's a bit tricky to get a fancy looking animation. But that one doesn't look too bad (DEMO).
var expElem = $(".hover-spell");
var exp = expElem.text();
var run = false;
expElem.empty();
for(var i = 0; i <= exp.length; i++) {
expElem.append('<span>'+exp.charAt(i)+'</span>');
}
expElem.mouseover(function() {
if(run === true) return false;
run = true;
var stepDuration = 300;
var counter = 0;
(function anim(){
if(counter == exp.length -1) return false; //Remove -1 to get last "e" animated
counter++;
var nth = exp.length;
var elem = $('span:nth-child('+nth+')', expElem);
elem.slideUp(stepDuration, function() {
(function() {
if(counter == 1) return elem.prependTo(expElem);
else return elem.insertAfter($('span:nth-child('+(counter-1)+')', expElem));
})().slideDown(stepDuration, anim);
});
})();
});
To get it working with hover(including mouseleave) is a bit more complicated. You could also try something with storing the position and then slide them over each other but again a bit more complicated.
<span id = "spell">olleh</span> //hello in reverse
<script type="text/javascript">
var newText;
var text = null;
text = document.getElementById("spell").innerHTML;
for (var i = text.length - 1; i >= 0; i--) {
if (i == text.length - 1) {
newText = text.substr(i, 1);
}
else {
newText = newText + text.substr(i, 1);
}
}
alert(newText);
</script>
write this script in body tag...
I am designing a language learning site. I want to have it when someone enters text into the text box it starts to roll over certain images. Take a look at my sample below
http://imageshack.us/photo/my-images/827/hiraganaquiz2.jpg/
So, when the user enters "na" the first symbol highlights as you see in my sample. When he enters "ma" the second symbol should highlight/rollover. I want all the symbols to stay rolled over while the correct text is entered. so if the user types "nama" the first two symbols should be rolled over to show they got it correct and once the last correct text is entered all three will be rolled over.
Can this by done? I will accept advanced and simple methods.
$(document).ready(function() {
var text = ['na', 'ma', 'ba'];
$("#elemID").on('keyup', function() {
var typed = this.value;
$.each(text, function(index, item) {
if (typed.indexOf(item)!=-1) {
$('li', 'ul').eq(index).find('img').addClass('correct');
}else{
$('li', 'ul').eq(index).find('img').removeClass('correct');
}
});
});
});
FIDDLE
EDIT:
At the top of your page, in the <head> section, add:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
Then wrap the code in document.ready, see the edited code above on how to do that ?
On change of the input box, you could do something like this: (totally untested)
var parts = ["na", "ma", "blah"];
var start = 0;
for (var i = 0; i < parts.length; i++) {
var currentPart = parts[i];
var $img = $(".images img:nth-child(" + i + ")");
var end = start + currentPart.length;
if (str.length >= end && str.slice(start, start + currentPart.length) == currentPart) {
$img.addClass("highlight");
} else {
$img.removeClass("highlight");
}
start += currentPart.length;
}