Image Hide in and hide out using event handler - javascript

I am working on a web page which contains a list of items and sub items for display. In the Div element, I am setting up the values, image. Using the image show and hide option On click event handler is triggered. This seems to be working fine with IE9, but doesn't work with other browsers (FireFox, Chrome and safari).
<div id="Type_A Medicine" value="H" entity="Type A Medicine" onClick="showHide(this,'MIE_Type_A Medicine')"><img src='<%=request.getContextPath()%>/images/plus.gif'>Type A Medicine</div>
function showHide(ctrl,id)
{
if (ctrl.value == "H")
{
ctrl.value = "S";
ctrl.innerHTML = "<img src='<%=request.getContextPath()%>/images/minus.gif'>" +ctrl.getAttribute("entity");
showBlock(id);
}
else if (ctrl.value == "S")
{
ctrl.value = "H";
ctrl.innerHTML = "<img src='<%=request.getContextPath()%>/images/plus.gif'>" + ctrl.getAttribute("entity");
hideBlock(id);
}
}
function hideBlock(blockId)
{
var str = "document.all." + blockId + ".style.display='none'";
eval(str);
}
function showBlock(blockId)
{
var str = "document.all." + blockId + ".style.display=''";
eval(str);
}
I still couldn't figure out the difference with the list of browsers. Kindly help...

I'm guessing it is because you use an invalid ID syntax. ID's cannot have spaces. If you use invalid HTML you can't expect javascript to work the same way across browsers.
id="Type_A Medicine"
Also, you never post the code for showBlock or hideBlock where you pass the ID in. Can't tell what goes wrong there without code.

To retrieve non-standard attributes, you should use .getAttribute() rather than trying to access them as properties.
So ctrl.entity should be ctrl.getAttribute("entity") and the same for other non-standard attributes. Run this example in Chrome: http://jsfiddle.net/jfriend00/Lxna7/.
Also, you should remove the space from your ID value as that's not a legal character and makes the id unusable in many circumstances (where a space is a delimiter between identifiers).

Try closing correctly the image tags to see if that fix the problem:
<img src="path/file.html" />

Related

IE11 Form Templating, innerHTML & outerHTML issue

I made a big form and I need a little templating to get it to work.
Like so
So I want to have an HTML DIV in my HTML code with the id="sponsor_template", read it and add it to the button.
Here is my js-code
var sponsorBTN = document.querySelector('[name="sponsors_add"]');
if (sponsorBTN !== null) {
sponsorBTN.addEventListener('click', function () {
var s_template = document.querySelector('[id="sponsor_template"]');
sponsorBTN.insertAdjacentHTML('beforeBegin', s_template.outerHTML.replace('id="sponsor_template"', 'name="sponsor"')
.replace('display:none', ''))
})
}
It works perfectly on any browser except for IE.
The only thing I know, where the issue could be is innerHTML / outerHTML because my output is incomplete when I console.log them in IE.
So it just cuts off after the 7'th line of HTML.
Here is the JSFiddle to this issue: https://jsfiddle.net/tdxkiller/b5m0t7xm/
This line is your problem:
s_template.outerHTML.replace('id="sponsor_template"', 'name="sponsor"').replace('display:none', '')
I'm not sure why it has a problem with "display:none"; I think there's some problem with the ":" character. However, I changed it to the below and it worked:
s_template.outerHTML.replace('id="sponsor_template"', 'name="sponsor"').replace('none', 'block')

Jquery altering background-url in IE

I ran into a problem using jquery in IE for a background-url. I have some html (that contains a style with a background-url) that I make a jquery object from. After that I change some properties in this object and want back the outerhtml. This all works fine in chrome, but in IE it changes the background url a bit (removing slashes and adding quotes) because of this the url is not working anymore. I can add more slashes for IE, but I was wondering why this happens and if there is a better solution?
So the following peace of code will give the same html back in chrome as was put in, but in IE it has been altered:
function test() {
var logo = '<div class=\"item__img\" style=\"background-image: url(graphic?path=avatars\\OSDAFIJ-Employee_Large.JPEG?ts=1433171332313)\"></div>';
var $logo = $(logo);
var logoOuterHtml = $logo.prop('outerHTML');
console.info(logo + " || " + logoOuterHtml);
alert(logo === logoOuterHtml);
}
test();
Fiddle: https://jsfiddle.net/v7fs4xvr/

Replace text in textarea on his exact position [duplicate]

I'm trying to use Javascript to replace the selected text in an arbitrary selected TEXTAREA node in Chrome (! not a content editable div !) The code fragment I see repeated in lots of places to replace selected text basically does this:
var sel = window.getSelection();
var range = sel.getRangeAt(0);
range.insertNode( document.createTextNode("test "));
However, this does not work for input fields such as TEXTAREA or INPUT TYPE=TEXT. The text is inserted BEFORE the TEXTAREA instead of inside it.
There is an alternative method to modify the selection text inside a text area using textarea.selectionStart and textarea.selectionEnd. However, these require figuring out which textarea element is actually active/selected. Chrome/Webkit document.activeElement seems to be broken and has been broken for a long time. I can't figure out any workaround to find the "currently selected textarea". See the bug here...
http://code.google.com/p/chromium/issues/detail?id=14436
You can see a micro-demo of the problem I'm trying to solve here.
http://dj1.willowmail.com/~jeske/_drop/insertIssue/1.html
http://ajaxandxml.blogspot.com/2007/11/emulating-activeelement-property-with.html
Any thoughts on this?
Given a webpage with an arbitrary bit of text selected in an arbitrary TEXTAREA node, without knowing ahead of time what textarea the focus is in, how do I find the active textarea and replace the selected text with some other text?
(( FYI: I'm using this code in a Chrome extension. An in-page javascript content script is extending the page javascript, so I have no idea what the page structure is ahead of time. It needs to work for any webpage. ))
I think the problem you may be having is that the active element changes as a result of clicking the button before your code runs. If you instead use the mousedown event and prevent the default button action, it works fine in Chrome:
http://jsfiddle.net/b3Fk5/2/
It appears that as of 8/23/2012, Chrome does not properly support activeElement, as it is often set to "body" when it shouldn't be.
There may also be some challenges because in my chrome extension, right-clicking to get a context menu might be altering the activeElement.
The solution was to provide a focus handler to create a more reliable activeElement in Chrome, and then use direct interaction with the TEXTAREA to handle the selection replacement.
var dActiveElement = null;
function _dom_trackActiveElement(evt) {
if (evt && evt.target) {
dActiveElement = evt.target;
console.log("focus on: " + dActiveElement.nodeName +
" id: " + dActiveElement.id);
} else {
console.log("focus else..");
}
}
if (document.addEventListener) {
document.addEventListener("focus",_dom_trackActiveElement,true);
}
function insertTextAtCursor(text) {
console.log("insertTextAtCursor : " + text);
if (dActiveElement.nodeName.toUpperCase() == "TEXTAREA") {
console.log("selection in textarea! id: " + dActiveElement.id);
var ta = dActiveElement;
var saveSelectionStart = ta.selectionStart;
var newvalue = ta.value.slice(0,ta.selectionStart) +
text + ta.value.slice(ta.selectionEnd,ta.length);
console.log("output : " + newvalue + ", len : " + newvalue.length);
var newSelectionEnd = ta.selectionStart + text.length;
ta.value = newvalue;
ta.selectionStart = ta.selectionEnd = (newSelectionEnd);
}
}

Javascript working on Firefox but not in Chrome and IE6

I have javascript that working fine in Firefox 3.x.x, but it does not work in IE*, Chrome, Safari. Simple alert work before calling function. Here is the code
function showDiv(div){
//alert(div);
document.getElementById(div).style.visibility='visible';
document.getElementById(div).style.height='auto';
document.getElementById(div).style.display='block';}
function hideDiv(div){
//alert(div);
document.getElementById(div).style.visibility='hidden';
document.getElementById(div).style.height='0px';
document.getElementById(div).style.display='none';
}
here is the html page code
<td align="center"><a onclick="showDiv('<?=$val['keyname']?>')" style="cursor:pointer;">Edit</a></td>
if I put alert() before showDiv('<?=$val['keyname']?>') then alert box is displayed but the function is not called in other browsers other than fire fox
Please tell me the solution for this.
The syntax looks okay to me.
Make sure there are not multiple elements with the same ID in the document and that your element IDs are valid.
There is nothing inherently wrong in the code you have posted. I suggest you post a reproduceable non-working example: the problem will be elsewhere in the page. Maybe the div ID string isn't unique (this is invalid HTML and will make behaviour unreliable); maybe there's some other script interfering, maybe you have event code firing this that's not written in a cross-browser way
However your attempts to hide an element in three different ways seem like overkill to me. Just a single display change would do it fine.
Another way to do it is to set className='hidden' or '', and use a CSS rule to map that class to display: none. The advantage of this is that you don't have to know whether the element in question is a <div> (that should revert to display: block), a <span> (that should revert to display: inline) or something else. (The table-related elements have particular problems.)
Maybe you could try that:
function showDiv(div) {
var obj = document.getElementById(div);
if (obj) {
obj.style.display = "block";
obj.style.height = "auto";
} else {
alert("DIV with id " + div + " not found. Can't show it.");
}
}
function hideDiv(div) {
var obj = document.getElementById(div);
if (obj) {
obj.style.display = "none";
} else {
alert("DIV with id " + div + " not found. Can't hide it.");
}
}
Do not call document.getElementById several times in the same function, use a variable to store the div element.
The if (obj) test will only execute the code if it has been found by document.getElementById(...).

detect tab characters with javascript in IE

I want to detect and replace tab characters in a bit of HTML like this:
<code>
something
{ something else
}
</code
Right now, I am using something like this:
$(this).html(replaceAll(trim($(this).html()), "\t", " "));
But IE, in all its cleverness, changes tab characters into spaces, and so doing the above is useless. Does anyone know how I can detect tab characters in the HTML source with javascript for IE?
So, jmaglasang gave me a good idea. He said IE respects whitespace in a pre tag. So, I thought why not insert a pre tag with javascript, read the html, then remove the pre tag afterward. It works but theres a catch - you have to use a setTimeout callback. Heres the code:
$("code").each(function()
{ $(this).wrap("<pre></pre>");
var element = $(this);
setTimeout(function() // read the html
{ var x = element.html().split("");
for(n in x)
{ alert(x[n].charCodeAt(0) + " '" + x[n] + "'");
}
}, 0);
});
The setTimeout is neccessary because for some reason, IE waits to re-render the html until after all the javascript finishes running. Incidentally, it also waits to execute any callbacks issued by setTimeout. I wish I knew how I could force IE to render the html immediately... If anyone knows I'd definitely appreciate it.

Categories