for example ,I have the following html
<HTML>
<HEAD>
<script type="text/javascript">
function trackElement(event){
event=event||window.event;
var target = event.explicitOriginalTarget||event.srcElement||document.activeElement;
var targetText = target.nodeValue||target.innerHTML;
alert(targetText);
}
</script>
</HEAD>
<BODY onclick="trackElement(event)">
<div>bbbbbb<div>cccccc</div>dddddddddd<div>eeeeeeeee</div></div>
</BODY>
</HTML>
When I clicked "bbbbbb",
On firefox ,I got "bbbbbb" alerted
which is exactly what I expected.
But on IE, I got
"bbbbbb<div>cccccc</div>dddddddddd<div>eeeeeeeee</div>"
When I clicked "dddddddddd",
On firefox ,I got "dddddddddd"
alerted which is exactly what I
expected.
But on IE, I got
"bbbbbb<div>cccccc</div>dddddddddd<div>eeeeeeeee</div>"
How can I get the same result with firefox on IE?
That's because the property "nodeValue" returns null for element nodes so you return innerHtml instead, which is gonna contain the whole html code inside an element. In Internet Explorer, your target is assigned by event.srcElement and hence is an element node, while it's a text node in FF. One way to solve the problem would be the following code :
function trackElement(event){
event=event||window.event;
var targetText;
var target = event.explicitOriginalTarget||event.srcElement||document.activeElement;
if(target.nodeType==3){
targetText = target.nodeValue
}else{
targetText = target.firstChild.nodeValue;
}
alert(targetText);
}
This way, you'd return the value if your assignment assigned a text node, and the text of the first child (which is what you're after) for an element node.
EDIT: Turns out I'm wrong. The problem is that event.srcElement returns the whole Element that's being clicked (event.explicitOriginalTarget being mozilla specific). From there, you need to retrieve the text. I see no easy way to do that if there are several texts in the element. If there is only one, it's a matter of iterating over the child nodes and displaying the text ones.
Please see comment about explicitoriginaltarget in crossbrowser-equivalent-of-explicitoriginaltarget-event-parameter.
In IE you get the Div element and the second one is in it, does this solution of separating the divs work for you? - the script is the same...
(This works both in IE and in FF)
<BODY onclick="trackElement(event)">
<div>bbbbbb</div>
<div>cccccc</div>
</BODY>
What about just substringing it?
<script type="text/javascript">
function trackElement(event){
event=event||window.event;
var target = event.explicitOriginalTarget||event.srcElement||document.activeElement;
var targetText = target.nodeValue||target.innerHTML.substr(0, target.innerHTML.indexOf("<"));
alert(targetText);
}
</script>
</HEAD>
<BODY onclick="trackElement(event)">
<div>bbbbbb<div>cccccc<p>Hellooo</p></div></div>
This seems to work, clicking ccccc returns "cccccc", and so on. Or did I completely miss the point?
EDIT: You also need to check if the element has any child elements before substringing it...
finally,I use offset to check which text node is clicked as below:
if ($.browser.mozilla) {
el = event.originalEvent.explicitOriginalTarget;
}else{
var parent =event.srcElement;
var left = event.pageX;
var top = event.pageY;
var offset=$(parent).offset();
for(var i=0;i<parent.childNodes.length;i++){
var n = parent.childNodes[i];
if ( n.nodeType == 1 ){
if($(n).offset().top>offset.top){
if($(n).offset().top>top){
el=parent.childNodes[i-1];
break;
}
}else if($(n).offset().top+$(n).height()>offset.top){
if($(n).offset().left>left){
el=parent.childNodes[i-1];
break;
}
}
}
el=n;
}
}
Related
So I'm writing some function that is working with Facebook's API. I was previously setting the onclick attribute by taking the parent and saying something along the lines of parent.innerHTML += "<a onclick = 'test("+parameter+")'>Previous</a>" and that worked fine. But I wanted to make it safer and more to standard so it is styled as follows:
function myMethod(link){
...
FB.api(link, function(response){
...
if(value != null){
var prev = document.createElement("a");
prev.innerText = "previous";
prev.setAttribute("id", "previous");
//prev.onclick = function(){test(this);}; doesn't work here
document.getElementById("facebook-photos").appendChild(prev);
}
//some other code (loops and stuff) including this
for(...){
var container = document.createElement("div");
container.classList.add("container");
container.classList.add("thing");
container.onclick = function(){test(this);}; // works here
}
//
if(document.getElementById("previous")){
document.getElementById("previous").onclick = function(){test(this);}; //works here
}
}
}
yet for some reason whenever I try and use this, clicking the element does nothing. Inspecting the element shows no "onclick" field but displaying the element in the console shows that the onclick field is not null. Nothing is covering the element and I've tried it as a div and as a button. When I try and do document.getElementById("previous") earlier, it still doesn't work. Why does this happen? Is it just the asynchronous nature of Javascript? The assignment in the middle works even though its relatively soon after the creation of the element, but the one at the beginning does not.
Is there a way in javascript to detect if a word/string was typed in a textarea? I want to detect the string <svg> being inputed in Ace editor or CodeMirror and then do something else. Sounds like it has been implemented but I don't know how.
It is possible in Javascript to bind to the key up/down/press/etc events on DOM objects. You have to set the appropriate attribute in the HTML.
<textarea onkeyup='checkText(this.value);'></textarea>
This is the key line that calls the Javascript function with the value (text) of the textarea.
Here is a complete example that demonstrates this use. Listening on Key Up is preferred since the new character will be in the text value before the function is called.
<html>
<head>
<script type='text/javascript' >
var oldText = '';
function checkText(text)
{
if(text.length >= 1)
{
if(text == '<svg>' && text != oldText)
{
alert("<svg> found");
}
}
oldText = text;
}
</script>
<body>
<textarea onkeyup='checkText(this.value);'></textarea>
</body>
</html>
I know this is somewhat similar to the others' answers, but it offers an alternative approach:
document.getElementById('textArea').onkeypress = function() {
if(/\<svg\>/i.test(document.getElementById('textArea').value) === true) {
// do whatever you want here
}
}
If you're not familiar with RegExes in JS, they're a great way to find certain strings in things - say, a user's input, like you want. The i flag after the creation ignores the case, just in case you didn't know. Also, putting this script in the head without an onload event or something of the sort won't work - there's nothing for the script to search, since the document hasn't been fully loaded yet.
Hope this helped!
You can compare what is typed with what you expect using the onchange event.
<html>
<script>
function checktext(){
var val = document.getElementById("textbox").value;
// val is what is in the textbox
// compare val here
// for example
if (val == "<svg>"){
alert(val);
}
}
</script>
<body>
<textarea id="textbox" onchange="checktext()"></textarea>
</body>
</html>
In CodeMirror, the "change" event is fired whenever the code changes. You can simply scan the content for the string you are interested in when this fires. Or, if you expect a huge document, and want this to be efficient, you can only scan the changed part of the document (taking care to handle the case where the string is on the boundary of the changed and unchanged parts).
cmInstance.on("change", function(cm) {
if (cm.getValue().indexOf("<svg>") > -1)
doSomething();
});
I have this wicked problem only in Firefox: when I add a link element to a contentEditable paragraph sometimes it breaks the paragraph in 2 or 3. This doesn't show any error and sometimes takes few seconds. Here's the code:
function changeSelectedText(type,text) {
var selObj = window.getSelection();
var selRange = selObj.getRangeAt(0);
var newElement = document.createElement(type);
if(type == "a") {
newElement.setAttribute('href', text.toLowerCase());
newElement.setAttribute('target', "_blank");
} else if(type == "span"){
newElement.setAttribute('class', "big");
}
var documentFragment = selRange.extractContents();
newElement.appendChild(documentFragment);
selRange.insertNode(newElement);
var range = document.createRange();
range.selectNodeContents(newElement);
selObj.removeAllRanges();
selObj.addRange(range);
}
Adding span works perfect but with links it sometimes causes this strange behavior. Any idea why?
Here's the link to jsfiddle like Mike suggested:
jsfiddle link
Found it :) The problem was that the button that I used for adding the link (the #link div at jsfiddle) sometimes got selected (only FF). I thought that the mousedown function should prevent this from happening but it didn't. So, what I did is I've added js to prevent selecting that button:
<div id="#link" onselectstart="return false;" ondragstart="return false;">Add Link</div>
If anybody has some better solution let me know ;)
I am trying to access an element in my Edge Animate animation (which is a menu bar) from the parent document. The element has an onClick event which is triggered depending on the #bookmark in the URL of the parent web page. My code works perfectly in Firefox but does not work in Internet Explorer(10). IE is unable to see any elements within the 'Stage' div whereas Firefox can.
This is the JavaScript code on my parent page: -
<script language='javascript'>
var thisPage = window.location.pathname;
var fullurl = document.URL;
var xxx = fullurl.substring(fullurl.indexOf('#'));
var pageString = xxx.replace("#", "");
pageString = pageString.replace("http://www.mydomain.com/portfolio/photography.html", "");
if (pageString == "corporate") {
window.onload = function() {
var iframe = document.getElementById('U10511_animation');
var innerDoc = (iframe.contentDocument) ?
iframe.contentDocument : iframe.contentWindow.document;
var corporateRectangle = innerDoc.getElementById('Stage_Corporate_Rectangle');
corporateRectangle.click();
}
};
</script>
The above code will select the Corporate tab in the menu when viewed in Firefox but not IE when the URL has the suffix #corporate.
When I insert an 'alert' for the variable 'corporateRectangle' in Firefox it returns [HTMLObj] and in IE it returns 'null'.
Any ideas anyone? Thanks.
Have you tried checking the console for an error of some sort to help you and us understand the error?
IE JavaScript often works differently than in other browsers. And iframes are particularly problematical. One possibility is that you are getting the wrong document, such that the documentyou are retrieving either does not exist or does not contain the element you are looking for. So you just have to do some debugging. Here is how I would proceed. Run your script in IE.
1) Determine whether innerDoc is iframe.contentDocument or iframe.contentWindow.document. Make sure innerDoc is not null. If it is, try to get the document a different way.
2) Assuming innerDoc is not null, enumerate all of the elements in innerDoc. You can do that as follows:
for(i = 0; i < innerDoc.all.length; i++) alert(innerDoc.all [i].id);
Make sure that the id you are looking for is actually in the document. I suspect it isn't and that you need to get a different document object under IE.
I assume you are stuck with having to use iframes. If not, I suggest you use a different approach as iframes can be very problematical and browser-specific in how they work.
internet Explorer gets confused over name and id - it is highly recommended to treat these two attributes as if they were the same.
You can fix it either by 1) ensure that there are no id/name conflicts in your document, or 2)
override IE's native getElementById-method.
Read more about it here.
Ok... thanks to everyone who left suggestions.
The issue was that the menu animation has a preloader. Firefox ignores the preloader whereas IE treats the preloader as onLoad being complete. Therefore the attempt to access the element ID is null as it hasn't been loaded yet.
I decided to approach the problem from a different tack and read my bookmark from within the animation. This turned out to be a very simple solution once I figured out that I had to put the code in the first frame of the animation NOT in creationComplete or compositionReady.
This was the code: -
var bookmark = parent.window.location.hash;
bookmark = bookmark.replace("#", "");
if (bookmark == "corporate") {
sym.play("corp");
}
yes, as simple as that.
I'm wondering whether it is possible to devise a script which will search a webpage for a certain string of text, and then click the link in the element id directly to its right.
Is this possible. Maybe javascript, php?
Please help, and thanks to all that do. :)
#Four_lo
Thanks for your reply. I'm sorry, maybe it's because I'm pretty new to javascript, but I can't really understand anything on the page you suggested.
I put together some javascript which will search the page for an element id and click the link within there.
<html>
<head>
<script type="text/javascript">
function init(){
var linkPage = document.getElementById('linkid').href;
window.location.href = linkPage;
}
onload=init;
</script>
</head>
<body>
GO HERE
I WANT TO CLICK HERE!
</body>
</html>
So basically, I need to search the page for GO HERE. Then, once this is found, I need to click the link in id="thisone", if that makes sense.
The above code works, and clicks the link within the id specified. However, I'd like to find certain text within that id, then move onto the next id, and click the link within that id.
It is possible. It will probably take some finesse but here is where you should start to access String you need. I believe regular expressions will be a must as well.
http://dom.spec.whatwg.org/#processinginstruction
http://domparsing.spec.whatwg.org/
Slightly more complicated than it needs to be:
function performAfterLinkWithText(text, perform) {
// get all the links
var $links = document.getElementsByTagName('a');
// scan them for your text
for(var i in $links) {
if($links[i].innerHTML === text) {
var $next = $links[i] // ready for loop
, terminateAfter = 20 // don't repeat forever
;
// keep checking the adjacent element
// because newlines show up as #text
do {
$next = $next.nextSibling;
} while( !$next.href && terminateAfter-- > 0 );
// do your thing
perform($next.href, $next); // window.location.href = $next.href;
}
}
}
// test -- performAfterLinkWithText('GO HERE', function(url, link) { console.log(url, link); });
performAfterLinkWithText('GO HERE', function(url) { window.location.href = $next.href; });
Or with jQuery:
window.location.href = $('a:contains("GO HERE")').next().attr('href')