How to add line break in title attribute using jquery - javascript

Please find my code below which adds a tooltip on mouseover event to a field in my survey engine.
What I want to achieve is add line breaks to the tooltip.
Any help is greatly appreciated.
var $j = jQuery.noConflict();
$j('#choice31QID405').mouseover(function() {
$j(this).attr('title','My name is Glenn. <Add a line break>. I am a good boy'. <Add a line break>. I live in New Delhi);
})
$j('#choice31QID405').mouseout(function() {
$j(this).removeAttr('title');
})

On modern browsers, you can just use a line break:
$("#target").attr("title", "Hello\nWorld");
<p title="Hello
World">
This one is hardcoded in the HTML.
</p>
<p id="target">
This one is added later
</p>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
That works fine on current (as of this writing) Chrome and Firefox, as well as IE11.

Use entity code
for line break.
Your code will look something like this:
$j(this).attr('title','My name is Glenn.
I am a good boy'.
I live in New Delhi);
Refer this FIDDLE

use <Hr> tag in HTML to set line
here is working example,
var $j = jQuery.noConflict();
$j('#choice31QID405').mouseover(function() {
$j(this).attr('title','My name is Glenn. <hr />. I am a good boy <hr /> I live in New Delhi');
$j('#test').html($j(this).attr('title'));
});
$j('#choice31QID405').mouseout(function() {
$j(this).removeAttr('title');
$j('#test').html("");
});
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
<title>JS Bin</title>
<body>
<div id="choice31QID405">Mouse over here</div>
<div id="test">Tooltip will show up here..</div>
</body>

Related

Swapping text for an image in Javascript

I'm looking for a way that I can search an entire HTML document for a specific word and then swap each instance of that word with an image.
The problem I have is that I don't know what content is there because it is a dynamic page where the content is edited elsewhere and the site just pulls it in so referencing classes and ids is difficult.
I created a simple example with text that could resemble the content but the problem I have is my script will replace the whole document (I believe because of .html?) and I just want it to replace that specific piece of text.
<p>hi</p>
<p>j</p>
var x = $('body:contains("hi")');
x.html('<img src="/Content/by_car.jpg" />');
Could someone point me in the right direction?
Thanks in advance
You need to replace the original html like so x.html(x.html().replace('hi', '<img src="/Content/by_car.jpg" />'));
Also, this will be bad if, for example you will have <p class="hiblo">hi</p>. In this canse it will replace hi in hiblo and hi inside p tag thus ruining your markup.
Generally you can use some kind of regex but it's still not recommended to parse html with regex.
Here is working code.
This code also makes sure that script and style tags don't get replaced otherwise page logic will be broken. So it is taken care of as well.
<html>
<head>
<script type="text/javascript" src="jquery-1.11.3.min.js" > </script>
<style></style>
</head>
<body>
<h1>hi</h1>
<div>hi</div>
<input type="button" onclick="return replaceWithImage()" value="replace with image"/>
<script type="text/javascript">
function replaceWithImage() {
var x = $('body').find(':contains("hi")');
x.each(function(){
if($(this).prop('tagName') != 'SCRIPT' && $(this).prop('tagName') != 'STYLE')
$(this).replaceWith('<img src="/Content/by_car.jpg" />');
});
return false;
}
</script>
</body>
</html>

In HTML/JavaScript, how do you dynamically set a header/paragraph element's text without overwriting anything else?

When you search for how to set a paragraph or header element's text dynamically, you keep coming across pretty much the same line of code:
document.getElementById("header").innerHTML = "some text";
This isn't entirely correct though. Take the following example:
<html>
<head />
<body>
<h1 id="header" />
<p id="p1" />
<script type="text/javascript">
document.getElementById("header").innerHTML = "header";
document.getElementById("p1").innerHTML = "p1";
</script>
</body>
</html>
The first JavaScript line pretty much deletes p1 from the page, even though p1 and header have nothing to do with each other in the raw HTML. When wrapping the second JavaScript line in a try...catch block, the error that's caught is:
document.getElementById(...) is null
The same problem exists when you use textContent instead of innerHTML. I'm a little surprised that everybody is saying that this is how you're supposed to change the text of an element when it really doesn't suit that purpose very well. What's the right way to set this up?
p and h1 are not "empty elements", meaning they're not closed in the same tag that opens them (like img and br). If you write them like that, they're not valid tags and the browser will ignore them (which is why document.getElementById can't find them). Try this instead:
<html>
<head></head>
<body>
<h1 id="header"></h1>
<p id="p1"></p>
<script type="text/javascript">
document.getElementById("header").innerHTML = "header";
document.getElementById("p1").innerHTML = "p1";
</script>
</body>
</html>
Change your html to this :
<h1 id="header"></h1>
<p id="p1"> </p>
And try your JavaScript code now they will work, because they are not empty elements.
I think the main issue you are having is with the way you are setting up the closing tags like so: <h1 id="header"/> with / instead of a closing statement. This is incorrect and you need to close it like so: <h1 id="header"></h1> The same is true for the <p> tag and many others. There are some exceptions to this rule which you can find here:
http://www.w3schools.com/html/html_elements.asp
Here is an example fiddle with the actual result!
http://jsfiddle.net/nd3Dq/

Trouble with a simple GetElementById thing real simple

Real simple but I'm starting with javascript so it should be quickly soved
I have this html:
<body>
<div id="content">
<div id="logo">
<noscript>
<img src="fin_palais.png"/>
</noscript>
</div>
</div>
</body>
and i want to select the div with an id of "logo" with javascript to then overwrite the <noscript> with the apropriate file ( a simple browser test to see if you can support SVG )
this innerHTML look like this:
document.getElementById('logo').innerHTML='<content to be added>';
Firebug send me this error: TypeError: document.getElementById("logo") is null
but its right there!
Thanks
okay so here is the full HTML:
<html>
<head>
<META CHARSET="UTF-8">
<title>Bienvenu au Fin Palais</title>
<script type="text/javascript" src="svg_support.js"></script>
<script type="text/javascript">getSvgSupport("fin_palais")</script>
</head>
<body>
<div id="content">
<div id="logo">
<noscript>
<img src="fin_palais.png"/>
</noscript>
</div>
</div>
</body>
</html>
and here's the full svg_support.js I've made;
function getSvgSupport(file)
{
var ua = navigator.userAgent;
if( ua.indexOf("Android") >= 0 )
{
var androidversion = parseFloat(ua.slice(ua.indexOf("Android")+8));
if (androidversion <= 2.3)
{
document.getElementById('logo').innerHTML='<img src="',file,'.png"/>';
}
} else {
document.getElementById('logo').innerHTML='<!--[if lt IE 9]><img src="',file,'.png"/><![endif]--><!--[if gte IE 9]><!--><embed src="',file,'.svg" type="image/svg+xml" /><!--<![endif]-->';
}
}
yes that is the only reason, and since you seem new to javascript I guess this would make more sense to you
window.onload=function(){
document.getElementById('logo').innerHTML='<content to be added>';
}
You see when your script runs you page has not loaded. so you must use window.onload.
Or you can use this too, if your code is in file.js:
<script defer src="file.js"> </script>
this makes sure your code doesn't run unless document is parsed.
You may be trying to run the javascript before the DOM has finished loading. Try this:
$(document).ready(function(){document.getElementById('logo').innerHTML='<content to be added>';});
This assumes you've included jQuery.
As #Thristhart said, you can also use window.onload. This is a built-in javascript event which happens AFTER $(document).ready() does, so you should be safe with that as well.
If using JQuery:
$(document).ready(function(){
$('div#logo').html('<content to be added>');
});
Or
$(function(){
$('div#logo').html('<content to be added>');
});
You don't have to load jQuery if you don't want to it seems like something is off with the chaining of the javascript. When I broke it apart it worked fine.
Fiddle: http://jsfiddle.net/DamianHall/GxghG/
var ele = document.getElementById('logo');
ele.innerHTML = 'content to be added';
Looking at other posts it is an onload issue. The JS fiddle did the onload for me so I didn't notice.​

JQuery - placing the cursor at the end of a textarea when it is focused on

First, some of you may notice that I reposted this question after deleting it. This is because it was mistakenly marked as a duplicate by someone who didn't bother to check - the question he linked to was about an <input> element; that solution does not work for textareas.
Anyway, consider the following code:
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
function caek() {
$('textarea[name=txt1]').val("cake");
$('textarea[name=txt1]').focus();
}
</script>
</head>
<body>
<div id="bar"></div>
<form name="frm1" id="cake">
<textarea name="txt1"></textarea>
</form>
<input type="button" value="Activate"
onclick="caek()">
</body>
</html>
When you run that, you will notice that the cursor is pushed to the start of the textarea, before the text. How can I make it come after all the text, at the end of the textarea? A non-inline solution would be optimal, but anything will do.
And a standalone solution (no plugins etc) would be perfect.
This is working for me.
function caek() {
txtArea = $('textarea[name=txt1]');
txtArea.val("cake");
txtArea.focus();
tmpStr = txtArea.val();
txtArea.val('');
txtArea.val(tmpStr);
}
This works.
$ta.text($ta.text()).focus()
Demo: http://jsfiddle.net/elclanrs/WWsBa/
You can use the rangyinputs jQuery plugin to do this in a cross platform way.
There's a demo here:
http://rangyinputs.googlecode.com/svn/trunk/demos/textinputs_jquery.html
Set the start and end to the same number and it'll set the cursor to that point (though it doesn't focus the textarea, so you have to tab into it to see the effect). In your case, you'd want to set it to the length of the text.

How to replace Current script tag with HTML contents generated by the same script

I want to replace the current script tag with the HTML contents generated by the same script.
That is, my Page is
<html>
<body>
<div>
<script src="myfile1.js"></script>
</div>
<div>
<script src="myfile1.js"></script>
</div>
</body>
</html>
Inside each .js file corresponding html contents are generated. I want to put the contents as the innerHTML of the parent div. But can't set id for the parent div because the page is not static. So the current script tag must be replaced with the HTML content. How can I do this?
For each script tag src is the same. So can't identify with src. These scripts displays
some images with text randomly. Scripts are the same but displays different contents in divs on loading
Please help me
try inside of myfile1.js:
var scripts = document.getElementsByTagName( "script" );
for ( var i = 0; i < scripts.length; ++ i )
{
if ( scripts[i].src == "myfile1.js" )
{
scripts[i].parentNode.innerHTML = "new content";
}
}
This is a great question for those trying to implement a JSONP widget. The objective is to give the user the shortest possible amount of code.
The user prefers:
<script type="text/javscript" src="widget.js"></script>
Over:
<script type="text/javscript" src="widget.js"></script>
<div id="widget"></div>
Here's an example of how to achieve the first snippet:
TOP OF DOCUMENT<br />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
// inside of widget.js
document.write('<div id="widget"></div>');
$(document).ready(function() {
$.getJSON('http://test.com?remote_call=1', function(data) {
$('#widget').html(data);
});
});
<br />BOTTOM OF DOCUMENT
Have a look at: http://alexmarandon.com/articles/web_widget_jquery/ for the correct way to include a library inside of a script.
document.currentScript has been available since 2011 on Firefox and 2013 on Chrome.
document.currentScript documentation at MDN
<!DOCTYPE html>
<meta charset="UTF-8">
<title>currentScript test</title>
<h1>Test Begin</h1>
<script>
document.currentScript.outerHTML = "blah blah";
</script>
<h1>Test End</h1>
Unfortunately a running JavaScript file is not aware of where it is running. If you use document.write() in the script, the write function will take place wherever the script runs, which would be one way to accomplish what you want, but without replacing the contents or being able to perform any actions on the enclosing DIV.
I can't really envisage a situation where you'd have such stringent restrictions on building a page - surely if the page is dynamic you could generate identifiers for your DIV elements, or load content in a more traditional manner?
Why not use Smarty?
http://www.smarty.net/
You can use javascript in Smarty templates, or just use built-in functions.
Just take a look at http://www.smarty.net/crash_course
poof -- old answer gone.
Based on your last edit, here's what you want to do:
<html>
<head>
<!-- I recommend getting this from Google Ajax Libraries
You don't need this, but it makes my answer way shorter -->
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
function getRandomContent(){
// I expect this is the contents of your current script file.
// just package it into a function.
var rnd = Math.random();
return "[SomeHtml]";
}
$('.random').each(idx, el){
$(this).html(getRandomHtmlContent());
});
});
</script>
</head>
<body>
<div class="random">
</div>
<div class="random">
</div>
</body>
</html>
If you don't mind the script tag remaining in place you can use something as simple as document.write().
myfile1.js:
document.write("<p>some html generated inline by script</p>");
It will do exactly what you need.

Categories