Reputation: 658
I need to put over a -responsive- image a string like "video", which is also his alt tag. for example:
<img src="my_image" alt="VIDEO">
and i should have my image and in the center (vertical and horizontal) the string "VIDEO" used as alt. I don't know how to use jquery, i've searched a lot but nothing is exactly what i need.
See that I don't need a CSS solution!
I've my reason, but I need jquery solution. I've tryed but nothing... If I write:
<script>
$(function () {
var info = $("#informa");
if (info.length == 0) {
info = $("<span />").addClass("informa");
$("body").append(info);
}
info.hide();
$(".hover_text").bind("mouseenter", function () {
var p = GetScreenCordinates(this);
info.html(this.alt);
info.show();
info.css("width", $(this).width());
info.css({ "left": p.x, "top": p.y + this.offsetHeight - info[0].offsetHeight });
});
$(".hover_text").bind("mouseleave", function () {
info.hide();
});
});
function GetScreenCordinates(obj) {
var p = {};
p.x = obj.offsetLeft;
p.y = obj.offsetTop;
while (obj.offsetParent) {
p.x = p.x + obj.offsetParent.offsetLeft;
p.y = p.y + obj.offsetParent.offsetTop;
if (obj == document.getElementsByTagName("body")[0]) {
break;
}
else {
obj = obj.offsetParent;
}
}
return p;
}
</script>
and my image is:
<img src="myimage.jpg" class="hover_text" alt="Collection">
it appears right but in the top.
Upvotes: 1
Views: 100
Reputation: 3120
You need to add absolute positioning to the span
, to remove it from the regular text flow. Add the following line:
info.css("position", "absolute");
And you get your span
above your image. The positioning is just a matter of correct calculation.
Edit:
To center it horizontally, just add text-align: center
to the element, since it is already as wide as the image by doing this info.css("width", $(this).width());
. For vertical centering, i assume that it can have multiple lines, so you need to add half of the height of the image and then substract half of the height of the text on the image.
Full code here: http://jsfiddle.net/sQwW6/
Edited lines:
info.css("text-align", "center");
info.css({ "left": p.x, "top": p.y + $(this).height()/2 - info.height()/2 });
Upvotes: 1
Reputation: 863
Use this modified script:
$(function () { var info = $("#informa"); if (info.length == 0) { info = $("").addClass("informa"); $("body").append(info); } info.hide(); $(".hover_text").bind("mouseenter", function () { var p = GetScreenCordinates(this); info.html(this.alt); info.show(); info.css("width", $(this).width()); info.css("position",'absolute'); info.css({ "top": info[0].offsetWidth-p.x, "left": p.y - info[0].offsetHeight }); }); $(".hover_text").bind("mouseleave", function () { //info.hide(); }); }); function GetScreenCordinates(obj) { var p = {}; p.x = obj.offsetLeft; p.y = obj.offsetTop; console.log(p); p.x = $(obj).width()/2; p.y = $(obj).height()/2; console.log(p) return p; }
Upvotes: 1