I'm using the Google Image Search API, and largely copied this code, which builds the search results in my page.
for (var i = 0; i < results.length; i++) {
// For each result write it's title and image to the screen
var result = results[i];
var linkContainer = document.createElement('div');
var title = document.createElement('div');
// We use titleNoFormatting so that no HTML tags are left in the title
title.innerHTML = result.titleNoFormatting;
var newImg = document.createElement('img');
newImg.src = result.tbUrl;
newImg.className = 'googleSearchResult';
newImg.title = 'newTitle';
newImg.alt = 'newAlt';
var newLink = document.createElement('a');
newLink.href = "temp_url";
newLink.appendChild(newImg);
contentDiv.appendChild(newLink);
}
In the following lines,
newImg.src = result.tbUrl;
newImg.className = 'googleSearchResult';
newImg.title = 'newTitle';
newImg.alt = 'newAlt';
the first two, which set the image src and class, work fine, but the second two, which should set the title and alt of the image, don't work at all. Can anyone see why this would be happening? Thanks for reading.
EDIT:
Here is the HTML when inspected in Firefox through Firebug:
<img alt="" src="http://images.google.com/images?q=tbn:_HZix2CrLSLSOM::bestonlinetvseries.com/deadwood/deadwood_s01.jpg" class="googleSearchResult">
Here is the HTML when inspected in Google Chrome
<img alt src="http://images.google.com/images?q=tbn:_HZix2CrLSLSOM::bestonlinetvseries.com/deadwood/deadwood_s01.jpg" class="googleSearchResult">
EDIT:
What I am trying to do here is store an extra bit of data in the HTML for the image, to be used in a jQuery plugin later. If anyone can suggest an alternative way to do this, that would be great as well.
I suspect the problem lies elsewhere. Consider this example, which works fine in the browsers I've tested (Firefox, Chrome, IE):
var link = document.createElement("a");
link.href = "http://stackoverflow.com";
var img = document.createElement("img");
img.title="Hello";
img.alt="alt Hello";
img.src="http://jsfiddle.net/img/sprites.png";
link.appendChild(img);
document.body.appendChild(link);
alert(img.getAttribute("alt"));
alert(img.getAttribute("title"));
I would recommend checking to see if anything might be in front of the link/img element, as this would stop a tooltip from appearing on hover.
In response to your last edit: if you're just trying to store data associated with an image for later use you could use jQuery's data method.
Try:
img.setAttribute('title', 'someTitle');
Appearantly, there's a difference between 'properties' and 'attributes' in DOM scripting.
Related
I am trying to load a svg via javascript. All I am getting is a blank screen, if I inspect it I see the code, but the svg is not rendering out. If you paste the link into the browser you can see the image. Any help is appreciated.
Thanks
var ajax = new XMLHttpRequest();
ajax.open("GET", "https://edit.meridianapps.com/api/floors/5649391675244544.svg?namespace=4906933713108992_1&hash=8f1c6699ad05ff6ca0ba9414884546b1&style=6711e01fe4271fa2fd1f299eff4296da&default_style=original", true);
ajax.send();
ajax.onload = function(e) {
var div = document.getElementById("svgContainer");
div.innerHTML = ajax.responseText;
}
<div id="svgContainer"></div>
As told by enxaneta in the comment div.innerHTML =ajax.responseText.replace(/ns0:/g,"") solves the problem as follows;
var ajax = new XMLHttpRequest();
ajax.open("GET", "https://edit.meridianapps.com/api/floors/5649391675244544.svg?namespace=4906933713108992_1&hash=8f1c6699ad05ff6ca0ba9414884546b1&style=6711e01fe4271fa2fd1f299eff4296da&default_style=original", true);
ajax.send();
ajax.onload = function(e) {
var div = document.getElementById("svgContainer");
div.innerHTML = ajax.responseText.replace(/ns0:/g,"");
}
<div id="svgContainer"></div>
This issue seems to be unrelated to the Ajax call. Your code works with another image URL.
The problem appears to be with the SVG in question. Including it via an img tag works fine. Direct inclusion of the SVG markup inside the HTML shows the same problem as you described.
Chrome and Firefox both display the large viewbox, but do not render any image contents.
The SVG in question prefixes all SVG tags with the namespace prefix ns0. As a commenter suggested, removing this prefix from all tags is successful - Chrome and Firefox display the image.
However, a simple text replacement as suggested is a weak solution: if the prefix changes (it's an arbitrary string set by the creator of the SVG), the image will again not be displayed. Furthermore, the text replacement may remove occurrences of ns0 in the image source that are not a namespace prefix, possibly breaking the image or altering its contents.
While I could not find an answer to the canonical way to go about inlining this kind of SVG files, I'd recommend using an image tag and setting the source to the URL.
<img id="svgContainer">
var img = document.getElementById("svgContainer");
img.src = "https://example.com/image.svg";
Check your CSS file for the id 'svgContainer' whether you had given some style or not.
Your issue more or less seems like a styling issue.
The issue is you need to first import the document i.e the responseXML is in another DOM document.
To insert into your document you need to use document.importNode
For more clarification, you can follow this answer.
var ajax = new XMLHttpRequest();
ajax.open("GET", "https://edit.meridianapps.com/api/floors/5649391675244544.svg?namespace=4906933713108992_1&hash=8f1c6699ad05ff6ca0ba9414884546b1&style=6711e01fe4271fa2fd1f299eff4296da&default_style=original", true);
ajax.onload = function() {
var svg = ajax.responseXML.documentElement;
var div = document.getElementById("svgContainer");
svg = document.importNode(svg, true); // tried and tested in Chrome only . Need to check for other browsers
div.appendChild(svg);
};
ajax.send();
Hello sorry for maybe a stupid question but i can't seem to find a easy solution.
The meaning of my exercise is to put 3 thumbnails on my website, but when I move over the images they need to expand in size (so i have a thumbnail version of the picture and the normal size). The normal size picture has to be on the
<p id="groot"></p>
This do work correctly, the only problem is that the pictures keep showing up when i move over it. So when I move out of the thumbnail the picture need to dissapear. Is there a function or something that get the site to the original state or any solution? Thanks in advance. I hope I explained it clearly.
This is my first question on stackoverflow, so if you have tips for a complete noob :)
This is the body of my HTML code:
<body>
<p><img id="foto1" src="images/thumb-bones.jpg" alt="bones"/>
<img src="images/thumb-castle.jpg" alt="castle"/>
<img src="images/thumb-mentalist.jpg" alt="mentalist"/>
</p>
<p id="groot"></p>
</body>
This is the JS code:
addEventListener("load", init, false);
function init() {
let foto1 = document.getElementsByTagName("img")[0].addEventListener("mouseover", actie, false);
let foto2 = document.getElementsByTagName("img")[1].addEventListener("mouseover", actie2, false);
let foto3 = document.getElementsByTagName("img")[2].addEventListener("mouseover", actie3, false);
foto1.addEventListener("click", uit, false);
}
function actie(event) {
let plaats = document.getElementById("groot");
let element = document.createElement("img");
element.src = 'images/image-bones.jpg';
plaats.appendChild(element);
}
function actie2(event) {
let plaats = document.getElementById("groot");
let element = document.createElement("img");
element.src = 'images/image-castle.jpg';
plaats.appendChild(element);
}
function actie3(event) {
let plaats = document.getElementById("groot");
let element = document.createElement("img");
element.src = 'images/image-mentalist.jpg';
plaats.appendChild(element);
}
Use a mouseout handler and, in the handler, remove all children from that element. An easy way to do that is to assign "" to innerHTML. So for instance:
function actie_off(event) {
document.getElementById("groot").innerHTML = "";
}
Hook that up to all three thumbnails.
If you don't want to use innerHTML, this question's answers give alternatives.
You might consider mouseenter and mouseleave instead of mouseover and mouseout. Probably doesn't make much difference here, it's just that mouseover repeats as the mouse moves across the thumbnails, and the bubbling of mouseout can be confusing with nested elements (not currently relevant for you). See the links for details.
Another thing to consider is to store the fullsize image URL on the thumbnail img elements as a data-* URI, like this:
<img id="foto1" src="images/thumb-bones.jpg" alt="bones" data-fullsize="images/image-bones.jpg"/>
Then you can use a single handler for all of your img elements instead of three separate ones:
function actie(event) {
let plaats = document.getElementById("groot");
let element = document.createElement("img");
element.src = this.getAttribute("data-fullsize"); // Getting the fullsize URL
// from the image the event
// relates to
plaats.appendChild(element);
}
I have Javascript code that opens ISBNs of books on Amazon using hyperlinks (feel free to try, for example: 0133098648). I would like the URL to open up on a new window with all links clicked in a new tab on that same window. It appears one can only open in a new tab of the current window, or a new window every time.
Is what I am looking to do even possible? I've been reading that something like this is restricted by browsers for security reasons; Maybe there's a work around? I've been pulling my hair out trying to find a solution for this, if I could it would make my life much more easier.
A picture to describe my question: http://imgur.com/a/5lUP4
Please use JSfiddle example: http://jsfiddle.net/mq1efed2 ( Code does not work on Stackoveflow)
<html>
<div><b>ISBN Hyperlinker</b></div>
<textarea id=numbers placeholder="paste isbn numbers as csv here" style="width:100%" rows="8" >
</textarea>
<div><b>Hyperlinked text:</b></div>
<div id="output" style="white-space: pre"></div>
<script>
//the input box.
var input = document.getElementById('numbers');
var output = document.getElementById('output')
var base =
'https://www.amazon.ca/s/ref=nb_sb_noss?url=search-alias%3Daps&field-keywords='
//adding an event listener for change on the input box
input.addEventListener('input', handler, false);
//function that runs when the change event is emitted
function handler () {
var items = input.value.split(/\b((?:\d\s*?){10,13})\b/gm);
// Build DOM for output
var container = document.createElement('span');
items.map(function (item, index) {
if (index % 2) { // it is the part that matches the split regex:
var link = document.createElement('a');
link.textContent = item.trim();
link.setAttribute('target', '_blank');
link.setAttribute('href', base + item.replace(/\D+/g, ''));
container.appendChild(link);
} else { // it is the text next to the matches
container.appendChild(document.createTextNode(item))
}
});
// Replace output
output.innerHTML = '';
output.appendChild(container);
}
handler(); // run on load
</script>
</html>
No, this isn't possible. Web pages cannot dictate whether or not content opens up in tabs or new windows. It's up to the user/browser to decide.
At best, you can open a new window with window.open(), but that doesn't give you control over tabs in a specific window later.
I can add an a element in js via this:
var mydiv = document.getElementById("myDiv");
var aTag = document.createElement('a');
aTag.setAttribute('href',"yourlink.htm");
aTag.innerHTML = "link text";
mydiv.appendChild(aTag);
But i want also make sure that this link opens in a new page. How can i achieve this?
aTag.setAttribute("target", "_blank");
DEMO: http://jsfiddle.net/dWDAQ/
This piece of code works for every browser except IE7. In IE7, the user is redirected to http://www.youtube.com. Oh, and it doesn't just redirect the frame, the entire page is redirected! Any thoughts? Ideas? Alternate patterns?
Please help me. IE is killing my will to live.
$('.youtube .cue a').live('click', function(e) {
e.preventDefault();
var $this = $(this);
var $area = $this.parents('.youtube');
var $caption = $area.find('.videoDescription');
var $li = $this.parents('li:first');
var vid = $.trim($(this).attr('href').replace('#', ''));
var title = $li.find('.title').text();
var time = $li.find('.time').text();
var description = $li.find('.description').text();
var $frame = $('<iframe></iframe>').attr({
width:595,
height:350,
frameborder: 0,
src: 'http://www.youtube.com/embed/' + vid
});
if (!hasFlash) {
$area.find('.captioned').html('Please install Flash.');
}
else {
$area.find('.captioned').html('').append($frame);
}
$caption.find('.title').html(title);
$caption.find('.time').html(time);
$caption.find('.description').html(description);
});
It looks to me like this line:
var vid = $.trim($(this).attr('href').replace('#', ''));
is the problem. Retrieving the href from the <a> tag is going to return a fully qualified URL (including http:// and domain on the front). Then, in this line, you're going to add it onto the end of another fully qualified URL:
src: 'http://www.youtube.com/embed/' + vid
That's going to yield an odd result like this:
http://www.youtube.com/embed/http://www.domain.com/xxxxxx
for the iframe src= attribute which is likely not what you want.
What may be tripping you up is that retrieving the href from an <a href="index.html"> tag retrieves a fully qualified URL, even if the page source only has a relative URL. If you only want the path or filename from that link href, you will have to parse that off.
I've verified with a reconstruction of your your HTML and your code that if you give this sort of bad URL to the iFrame, it will redirect the whole page (even in Chrome). Here's the jsfiddle: http://jsfiddle.net/jfriend00/4P3dh/.
If you hit Run and then click the link that says "Click Me", it will redirect the whole page because of the bad URL on the iFrame.