Generating content from jQuery - javascript

I am working on a jQuery tooltip module for personal use. In my code I'm using jQuery's mousemove and mouseout functions in order to generate the tooltip. However, when I move my mouse over the element it hits the if statement in the build function and says that the tooltip should be there even though I can see in Firebug and in the Chrome Dev Tools that it's not.
$.fn.tooltip = function(userOptions)
{
var defaultOptions = {
position: '',
follow: true
};
var options = $.extend(defaultOptions, userOptions);
$(this).mouseenter(function()
{
var title = $(this).data('title');
build(title, options.position, options.follow);
var top, left;
var tooltip = $('#tooltip');
if (tooltip.hasClass('top'))
{
top = $(this).offset().top - ($(this).height() * 2) - 10;
left = $(this).offset().left;
}
else if (tooltip.hasClass('right'))
{
top = $(this).offset().top - ($(this).height() / 2);
left = $(this).offset().left + tooltip.width();
}
else if (tooltip.hasClass('bottom'))
{
top = $(this).offset().top + $(this).height() + 10;
left = $(this).offset().left;
}
else if (tooltip.hasClass('left'))
{
top = $(this).offset().top - ($(this).height() / 2);
left = $(this).offset().left - (tooltip.width() * 1.5);
}
tooltip.css('top', top).css('left', left).show();
});
$(this).mousemove(function(e)
{
if (options.position === "" || options.position === undefined || options.follow === true)
{
var title = $(this).data('title');
build(title, options.position, options.follow);
var top = e.pageY + 25;
var left = e.pageX + 10;
$('#tooltip').css('top', top).css('left', left).show();
}
});
$(this).mouseout(function()
{
$('#tooltip').hide();
});
function build(title, position, follow)
{
if ($('#tooltip'))
{
console.log("The tooltiop should be on the page.");
$('#tooltip-content > p').text = title;
}
else
{
console.log("Position is: " + position);
var markup = '<div id="tooltip" class=' + position + '">';
markup += '<div id="tooltip-content">';
markup += '<p>' + title + '</p>';
markup += '<span id="tooltip-arrow"></span>';
markup += '</div>';
markup += '</div>';
$('body').append(markup);
}
}
};
The original goal was to create the tooltip the first time the user moves over the element and then when the mouse moves away I wanted to hide the tooltip and move it out of the way until it's needed again. That's why I'm checking to see if it exists in the build function. I know I'm overlooking something, I just can't figure out what it is. Any suggestions?

In build function change the check in the if like:
if ($('#tooltip').lenght) {
that will return false if #tooltip is not yet appended to body and true if it is.
The $('#tooltip') will return always a jQuery object thus it will never be false but its length will be 0, thus false, if the tooltip element is not yet added to the body.
jsFiddle
Regards.

Related

Shifting a div to the left on click in angularjs

So I am trying to allow the user to shift a div to the left or right in angularjs. Right now I have the function below. It works on the first click but all it does is toggle every click and is saying left is NaN. What am I doing wrong here? Also if someone has a better solution for this please let me know.
vm.scrollSelector = function(e, direction) {
var target = document.getElementById('item-selector');
var left = target.style.left;
if(direction === 'left') {
left += 600;
target.setAttribute('style', 'left: ' + left + 'px');
} else {
left -= 600;
target.setAttribute('style', 'left: ' + left + 'px');
}
}
So I quickly found the answer just by looking at the docs. Left is returned as a string so all I had to to was do parseInt(left) + 600 and it worked.
vm.scrollSelector = function(e, direction) {
var target = document.getElementById('item-selector');
var left = target.style.left.match(/\d+/);
left = parseInt(left[0], 10)
if(direction === 'left') {
left += 600;
target.setAttribute('style', 'left: ' + left + 'px');
} else {
left -= 600;
target.setAttribute('style', 'left: ' + left + 'px');
}
}
First try to see what value target.style.left is returning. It might be returning value like '10px'. You need to convert this into a number first then perform the addition or subtraction.

Calculating positioning of the parent Div

Hi i want to calculate the position of the Div. Pardon me if i am not able to explain it properly but i will try to explain everything in the simplest way. I am creating sidepanel ad and to place the panels i want the position of the width. When i upload the script on my server then i get a small script which we place on the publisher website and where our script runs inside the iframe. I want to get the position of the div which has a class 'content'. Here is the screen shot.
in the above screenshot the yellow highlighted script is calculating the position of the div class="content" which is in red box. My code was working fine but on the publisher site it was not working fine and i was only able to get only two Divs whose id is like ebDiv..... (these divs are above the yellow highlighted js).
Then i found out to read the parentDiv in order to get the content positions.
i wrote this code.
var parentDoc = window;
while (parentDoc !== parentDoc.parent) {
parentDoc = parentDoc.parent;
}
parentDoc = parentDoc.document;
var parentDiv = parentDoc.getElementsByTagName('div');
var divs = [];
for (var i = 0; i < parentDiv.length; i++) {
if (parentDiv[i].className == "content") {
alert(parentDiv[i].offsetWidth);
alert(parentDiv[i].offsetLeft);
}
The width is calcuated as 1010 which is fine but i am just missing left positioning which i am getting using parentDiv[i].offsetLeft is 2.
Above the screenshot has width 1010 which is fine but left positioning is not correct.
i had this code to calculate the width.
function ReadDivPos(selector) {
var _divPos = "";
$(selector).each(function() {
var p = $(this).offset();
var w = $(this).width();
console.log("Top " + p.top) //top
console.log("left " + p.left) //left
console.log("right " + p.left + w) //right
console.log("offsetWidth " + w); //width
_divPos += "Left " + p.left + ",Width " + w + ",Avail Width " + window.screen.availWidth + ",Right " + (p.left + w) + "\\n";
});
return _divPos;
}
console.log(ReadDivPos(".content"));
when i am using the same code to calculate the positioning then it is not working .
var parentDoc = window;
while (parentDoc !== parentDoc.parent) {
parentDoc = parentDoc.parent;
}
parentDoc = parentDoc.document;
var parentDiv = parentDoc.getElementsByTagName('div');
var divs = [];
for (var i = 0; i < parentDiv.length; i++) {
if (parentDiv[i].className == "content") {
$(parentDiv[i]).each(function() {
var p = $(this).offset();
var w = $(this).width();
console.log("Top " + p.top) //top
console.log("left " + p.left) //left
console.log("right " + p.left + w) //right
console.log("offsetWidth " + w); //width
_divPos += "Left " + p.left + ",Width " + w + ",Avail Width " + window.screen.availWidth + ",Right " + (p.left + w) + "\\n";
}
}
Can someone me explain me how to fix this. Jquery/Javascript anythingwould be fine. I am not good in the frontend things so i am sorry if i could not explain it better. Thanks in advance
Here is a function used to get the position on the page of an element:
function getPosition(element) {
var xPosition = 0;
var yPosition = 0;
while (element) {
xPosition += (element.offsetLeft - element.scrollLeft + element.clientLeft);
yPosition += (element.offsetTop - element.scrollTop + element.clientTop);
element = element.offsetParent;
}
return { x: xPosition, y: yPosition };
}
Used like this:
var pos = getPosition(element);
var x = pos["x"];
var y = pos["y"];
I'm not sure if this is exactly what you need, but if not maybe you can tweak it to fit your situation

Watching for multiple elements without multiple if statements

I have a snippet that on scroll it checks wether an element is in the current viewport.
I now want to add multiple elements into the mix, but I wanted to avoid doing multiple if statements checking for each, I know the following code doesn't work but it is an example of how I would like to do it, is there a way of doing it this way?
var listOfPanels = $('#item2, #item2, #item3, #item4, #item5');
$(window).scroll(function(event) {
// if the element we're actually looking for exists
if (listOfPanels.length){
// check if the element is in the current view using the attached function
// and the event hasn't already fired
if (isElementInViewport(listOfPanels)) {
// do something
}
}
});
try this:
function isElementInViewport(el) {
var top = el.offsetTop;
var left = el.offsetLeft;
var width = el.offsetWidth;
var height = el.offsetHeight;
while(el.offsetParent) {
el = el.offsetParent;
top += el.offsetTop;
left += el.offsetLeft;
}
return (
top < (window.pageYOffset + window.innerHeight) &&
left < (window.pageXOffset + window.innerWidth) &&
(top + height) > window.pageYOffset &&
(left + width) > window.pageXOffset
);
}
var listOfPanels = $('#item2, #item2, #item3, #item4, #item5');
$(window).scroll(function(event) {
if (listOfPanels.length){
listOfPanels.each(function(){
if (isElementInViewport($(this)[0])) {
console.log($(this).attr('id') + ' in viewport');
}
});
}
});
(isElementInViewport js method brought from: How to tell if a DOM element is visible in the current viewport?)
hope that helps.

How to remove selected image on a div when you click on it?

I am fairly new to Javascript and would like to create a div whereby it allows a person to define points on it by clicking on the area within the div. An image will be added to represent the point clicked. Thereafter, if the person wants to remove this point, upon clicking on the image, it should be remove.
I have done the part whereby it allows a person to define the points based on a minor modification to an existing fiddle: http://jsfiddle.net/uKkRh/1/
Reference: jquery how to add pin to image and save the position to SQL
I also manage to remove all the images by click on the button.
However, I am still short of how to remove the image from the div when the person clicks on the image.
I have tried the following:
$('#container >img').click(function() {
var selectedImg = $(this);
selectedImg.remove();
return;
});
but it works itermitently.
Please see my JSfiddle for my sample. http://jsfiddle.net/WindSaviour/rUNsJ/19/
var point = [];
var id = 0;
$(document).ready(function() {
var output = $('#container');
$("#container").click(function(e) {
e.preventDefault();
var isPointPresent = false;
var x = e.pageX - this.offsetLeft;
var y = e.pageY - this.offsetTop;
console.log("Mouse Click Pos (x=" + x + ", y=" + y + ")");
for(var i=0; i< point.length; i++) {
if(x >= point[i].min_x && x<=point[i].max_x) {
if(y >= point[i].min_y && y<=point[i].max_y) {
isPointPresent = true;
point.splice(i,1);
break;
}
}
}
point[point.length] = { "x-pos": x, "y-pos":y, "min_x": x-25, "max_x": x+25, "min_y": y-83, "max_y": y};
if(isPointPresent) {
$('#container >img').click(function() {
var selectedImg = $(this);
selectedImg.remove();
return;
});
}
var img = $('<img>');
var left = x-25;
var top = y-83;
console.log("Img Start Pos (x=" + left + ", y=" + top + ")");
img.css('top', top);
img.css('left', left);
img.attr('src', 'http://www.clker.com/cliparts/P/w/G/0/N/o/google-map-th.png');
img.attr('id', id);
img.appendTo('#container');
/*
*/
id++;
})
});
$('#remove').click(function() {
$('#container > img').remove();
});
Try this http://jsfiddle.net/uKkRh/635/, but you need a newer verion of jQuery
$('#container').on('click', 'img', function (e) {
e.stopPropagation();
$(this).remove();
});

How to get amount of portions of a HTML element is visible in viewport

Is it possible to know whether or not an HTML element like image is viewable in current viewport or it will be visible on scroll?
If it is viewable completely or partially then how can I get the amount of portions is visible?
I am trying to explain it from the following image:
The two images at the bottom is partially visible within the viewport and these will be completely visible if one scroll down a little bit.
Now I want to get the the aforesaid information.
In the actual scenario I am trying to get the popup-zoom effect on hover of image in my album like google image search. Everything is fine, except if the images are placed in the described manner then the zoomed div also displaying in half.
Normal condition where image is completely in viewport:
And partially in viewport:
I really appreciate your help.
The code:
var albumDetailOnReady = function() {
$('.image').each(function(){
var photo = $(this);
var wrap = $(findParentByClassName(document.getElementById(photo.attr('id')), 'wrap'));
var row = $(findParentByClassName(document.getElementById(wrap.attr('id')), 'albumDetailRow'));
var visibleZone = $(wrap).find('.alDtlColumn');
var pictureBlock = $(visibleZone).find('.pictuteBlock');
var hiddenZone = $(wrap).find('.hiddenZone');
$(photo).load(function(){
if(177 > $(photo).width()){
var imgleft = ($(pictureBlock).width() - $(photo).width())/2 + 'px';
$(photo).css({'left': imgleft});
}
});
$(photo).hover(function(){
var y;
if($(photo).height() > $(photo).width()) {
y = ($(visibleZone).offset().top - 50) + 'px';
} else {
y = ($(visibleZone).offset().top + 50) + 'px';
}
var x;
if($(row).find('.wrap:first').attr('id') === $(wrap).attr('id')) {
x = ($(visibleZone).offset().left - 10) + 'px';
} else if($(row).find('.wrap:last').attr('id') === $(wrap).attr('id')) {
x = ($(visibleZone).offset().left - 50) + 'px';
} else {
x = ($(visibleZone).offset().left - 20) + 'px';
}
$(hiddenZone).css({
'top': y,
'left': x,
'position': 'absolute',
'z-index': '10'
});
$(hiddenZone).fadeIn('fast');
}, function(){
});
$(hiddenZone).hover(function(){},function(){
$(hiddenZone).hide().stop(true, true);
});
});
}
var findParentByClassName = function(element, clazz) {
while (element.parentNode) {
element = element.parentNode;
if (hasClass(element, clazz)) {
return element;
}
}
return null;
}
function hasClass(element, cls) {
var regex = new RegExp('\\b' + cls + '\\b');
return regex.test(element.className);
}
I am unable to show any HTML as I haven't have any, I am working in ADF framework.
But for an explanation:
I have two zone for each image: visible and hidden. Both of them are in a wrap. Now on hover an image I am showing the hidden div. The top and left of the hidden div is measured by the top and left of the visible div with some condition.
jQuery.Viewport
Very helpfull and lightweight jQuery plugin that makes an element as a handy viewport for displaying elements with absolute position. The plugin is hosted on GitHub. You can see it in action right there:
https://github.com/borbit/jquery.viewport

Categories