Wordpress - widget save button break jquery - javascript

So, I have a widget. I can add div's after click through .append
When I add for example 5 divs and click save all of them dissapear. Also I can't add another divs. I need to reload wpadmin page then I can add it again.
I found something like this but it seems to not working for me. Any ideas?
My js file
jQuery(document).ready(function($){
// basic add
$("button#remove").click(function(){
$(".marker").remove();
});
//add with position
var map = $(".map");
var pid = 0;
function AddPoint(x, y, maps) {
var marker = $('<div class="marker"></div>');
marker.css({
"left": x,
"top": y
});
marker.attr("id", "point-" + pid++);
$(maps).append(marker);
$('.marker').draggable({
stop: function(event, ui) {
var thisNew = $(this);
var x = (ui.position.left / thisNew.parent().width()) * 100 + '%';
var y = (ui.position.top / thisNew.parent().height()) * 100 + '%';
thisNew.css('left', x);
thisNew.css('top', y);
console.log(x, y);
}
});
}
map.click(function (e) {
var x = e.offsetX/ $(this).width() * 100 + '%';
var y = e.offsetY/ $(this).height() * 100 + '%';
AddPoint(x, y, this);
});
});

Related

Get correct click position on scaled image

This is how I get the click position when clicking on an image to do some image transformation. But my problem is, that the image has the CSS attribute max-width: 1000px. So the code works only for images which are smaller. For larger images the position result is not the real pixel which was clicked on.
My question is, if it is possible to calculate the correct click position for the natural sized image. An alternative would be to set some data attributes with the real image size like data-width: '1200px' and data-height: '1000px'. But still I have to do some calculation.
parentPosition = getPosition(event.currentTarget),
x = event.clientX - parentPosition.x,
y = event.clientY - parentPosition.y;
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 };
}
If you know natural size and current size, i think you can just do this:
naturalClickPosX = (naturalWidth / currentWidth) * currentClickPosX;
naturalClickPosY = (naturalHeight / currentHeight) * currentClickPosY;
Have a look at this JSFiddle
HTML
<img src="http://placehold.it/1200x1000" width="1000">
JavaScript
$('img').on("click", function(e){
var $img = $(this);
var currentClickPosX = e.pageX - $img.offset().left;
var currentClickPosY = e.pageY - $img.offset().top;
var currentWidth = $img.width();
var currentHeight = $img.height();
var naturalWidth = this.naturalWidth;
var naturalHeight = this.naturalHeight;
var naturalClickPosX = ((naturalWidth / currentWidth) * currentClickPosX).toFixed(0);
var naturalClickPosY = ((naturalHeight / currentHeight) * currentClickPosY).toFixed(0);
alert("Current X: " + currentClickPosX + " Current Y: " + currentClickPosY +
"\r\nNatural X: " + naturalClickPosX + " Natural Y: " + naturalClickPosY);
});
try this , will work on all sizes
$('.img-coordinate').click(function(e){
var parentOffset = $(e.target).parent().offset();
// here the X and Y on Click
X = e.pageX - $(e.target).offset().left;
Y = e.pageY - $(e.target).offset().top;
alert(X + ' , ' + Y );
});
working fiddel : https://jsfiddle.net/h09kfsoo/

how to animate image & change the direction from right to left

Please find the code, which iam facing issue with changing the direction of arrow, the arrow should change the facing from right to left once it reach the screen width. THE REQUIRED FUNCTIONALITY IS THE ARROW SHOULD NOT GO IN REVERSE it has to change its direction.
tried lot some one give solution.
http://jsfiddle.net/7xyuqe1k/5/
function AnimateFish() {
var Fish3 = $("[id^=fish]").not(".HoverFish"),
theContainer = $("#container"),
maxLeft = theContainer.width() - Fish3.width() - 50,
maxTop = theContainer.height() - Fish3.height(),
leftPos = Math.floor(Math.random() * maxLeft),
topPos = Math.floor(Math.random() * maxTop) + 100,
imgRight = "Assets/fish-glow3-right.gif",
imgLeft = "Assets/fish-glow3.gif";
/*Get position of the fish*/
//console.log(Fish3.position().left +" +"+leftPos);
//alert(Fish3.position().left);
if ($("[id^=fish]").position().left >= leftPos) {
$(this).css("background-image", 'url("' + imgRight + '")');
} else {
$(this).css("background-image", 'url("' + imgLeft + '")');
}
Fish3.animate({
"left": leftPos,
"top": topPos
}, 1800, AnimateFish);
}
There was a problem on fish's destination points(positions left & top) picking. First fish works properly since it's picking the destination point respective to itself, but rest of the fishes also were taking the destination points respective to 1st fish not themselves.
The working sample is available here http://jsfiddle.net/ravinila/7xyuqe1k/26/
$(document).ready(function(e) {
var newfishid = 0;
$('.post-button').click( function(e) {
var fish = $("<div/>", {"class":"large-fish fish", "id" : "fish"+(newfishid++)});
$('#container').append(fish);
fish.on("anim", function(e){
var _this = $(this),
theContainer = $("#container"),
maxLeft = theContainer.width() - _this.width() - 50,
maxTop = theContainer.height() - _this.height(),
leftPos = Math.floor(Math.random() * maxLeft),
topPos = Math.floor(Math.random() * maxTop) + 100,
imgLeft = "http://free-icon-download.com/modules/PDdownloads/images/screenshots/free-icon-download_left-arrow-blue.png",
imgRight = "http://www.newclassicdesign.com/r_arrow.png";
if (_this.position().left < leftPos) {
_this.css("background-image", 'url("' + imgRight + '")');
} else {
_this.css("background-image", 'url("' + imgLeft + '")');
}
_this.animate({
"left": leftPos,
"top": topPos
}, 2500, function(){
$(this).trigger("anim");
});
});
fish.trigger("anim");
fish.hover(function(e) {
$(this).stop();
}, function(e) {
$(this).trigger("anim");
});
});
});
I have taken a look at it and it looks like its a silly mistake. Your fiddle showed something was working since it changed something when the direction changed, so the basics are okay. You just forgot that there was an image tag inside you div that you're meant to be manipulating.
function AnimateFish() {
var Fish3 = $("#fish1").not(".HoverFish"),
theContainer = $("#container"),
maxLeft = theContainer.width() - Fish3.width() - 50,
maxTop = theContainer.height() - Fish3.height(),
leftPos = Math.floor(Math.random() * maxLeft),
topPos = Math.floor(Math.random() * maxTop) + 100;
imgRight = "http://www.newclassicdesign.com/r_arrow.png",
imgLeft = "http://free-icon-download.com/modules/PDdownloads/images/screenshots/free-icon-download_left-arrow-blue.png";
// below here you used $(Fish3), but Fish3 is already a JS object - you don't need to rewrap it.
// The biggest problem however, is that below that you used '$(this)', which won't work as there
// is no context defined (you're in an if, not a jQuery function).
// Replacing this with the same Fish3 does the job,
// as it already was a jQuery object anyhow.
// I have also changed your background from an image to red and green for testing purposes.
// As you can see, thats working. However, your image isn't changing..
// This is because you have an image inside you wrapper which you aren't changing.
if (Fish3.position().left >= leftPos) {
Fish3.css("background", 'green');
// So lets change the image...
Fish3.find("img").attr("src", imgLeft);
} else {
Fish3.css("background", 'red');
// So lets change the image...
Fish3.find("img").attr("src", imgRight);
}
Fish3.animate({
"left": leftPos,
"top": topPos
}, 1800, AnimateFish);
}
Check my comments inside the code to see what happened, but copying this into your fiddle and replacing the animation function did the trick.

Text Fadein/Fadeout at Random Positions

I'm attempting to put together a webpage that has text that pops up at random locations on the page, fade out, then appear again at a random location again. I found something that suits my purposes for example. I want something like this, but with text that I can manipulate and make a list out of with text-shadow effects if needed.
(function makeDiv(){
var divsize = ((Math.random()*100) + 50).toFixed();
var color = '#'+ Math.round(0xffffff * Math.random()).toString(16);
$newdiv = $('<div/>').css({
'width':divsize+'px',
'height':divsize+'px',
'background-color': color
});
var posx = (Math.random() * ($(document).width() - divsize)).toFixed();
var posy = (Math.random() * ($(document).height() - divsize)).toFixed();
$newdiv.css({
'position':'absolute',
'left':posx+'px',
'top':posy+'px',
'display':'none'
}).appendTo( 'body' ).fadeIn(100).delay(300).fadeOut(200, function(){
$(this).remove();
makeDiv();
});
})();
Fiddle
This is a second example of something similar, only it doesn't have random position.
$('li').each(function(){
var randomTop = $('div').height()*Math.random(); //random top position
var randomLeft = $('div').width()*Math.random(); //random left position
$(this).css({ //apply the position each li
top : randomTop,
left : randomLeft
});
});
Fiddle
I'm hoping to sort of splice the two together in order to get what I'm ideally looking for. Please forget the formatting as its my first time here and I'm trying to conform to the standards.
I'm not sure if I understand exactly what you're looking for but I "spliced them together."
Fiddle
(function fadeInDiv(){
var divs = $('.fadeIn');
var divsize = ((Math.random()*100) + 50).toFixed();
var posx = (Math.random() * ($(document).width() - divsize)).toFixed();
var posy = (Math.random() * ($(document).height() - divsize)).toFixed();
var maxSize = 30;
var minSize = 8;
var size = (Math.random()*maxSize+minSize)
var elem = divs.eq(Math.floor(Math.random()*divs.length));
if (!elem.is(':visible')){
elem.fadeIn(Math.floor(Math.random()*1000),fadeInDiv);
elem.css({
'position':'absolute',
'left':posx+'px',
'top':posy+'px',
'font-size': size+'px'
});
} else {
elem.fadeOut(Math.floor(Math.random()*1000),fadeInDiv);
}
})();
EDIT: Updated Fiddle URL

Stop function when pressing ctrl jQuery

So I am making a little game where you have to press Ctrl to stop a div from jumping randomly.
However I can't get it working...
The jumpRandom function works fine, until i put the randomJump(){return false;}; inside the if (event.ctrlKey) {}. What should I do to get it working?
js:
$(document).ready(function() {
function randomFromTo(from, to){
return Math.floor(Math.random() * (to - from + 1) + from);
}
$( "#goal" ).bind('mouseenter keypress', function(event) {
if (event.ctrlKey) {
randomJump(){return false;};
}
});
$('#goal').mouseenter(randomJump);
function randomJump(){
/* get Window position and size
* -- access method : cPos.top and cPos.left*/
var cPos = $('#pageWrap').offset();
var cHeight = $(window).height() - $('header').height() - $('footer').height();
var cWidth = $(window).width();
// get box padding (assume all padding have same value)
var pad = parseInt($('#goal').css('padding-top').replace('px', ''));
// get movable box size
var bHeight = $('#goal').height();
var bWidth = $('#goal').width();
// set maximum position
maxY = cPos.top + cHeight - bHeight - pad;
maxX = cPos.left + cWidth - bWidth - pad;
// set minimum position
minY = cPos.top + pad;
minX = cPos.left + pad;
// set new position
newY = randomFromTo(minY, maxY);
newX = randomFromTo(minX, maxX);
$('#goal').fadeOut(50, function(){
$('#goal').fadeIn(700);
});
$('#goal').animate({
left: newX,
top: newY,
duration: 500
});
}
});
Try this:
$("#goal").bind('mouseenter keypress', function (e) {
randomJump(e);
});
function randomJump(e) {
if (!e.ctrlKey) {
//do normal stuff
} else {
//depending on how permanent you need this to be...
//$("#goal").unbind('mouseenter keypress');
}
return !e.ctrlKey;
}

calculating the top-right offset of div while rotating it

I want to calculate the top-right position of div , i can calculate it, if it is not rotated with:
$("div").offset().top + $("div").width();
But when we rotate div then , how we can calculte top-right position ?
Rotate code:
$("div").slider({
slide: function(e,u){
$(this).rotate({ angle : u.value});
}
});
You can try this:
JavaScript
$(".slider").slider({
min: 0,
max: 180,
slide: function(e,u){
$(this).rotate({ angle : u.value});
calculateTopLeft(u.value);
}
});
var pointer = $('.pointer');
var slider = $('.slider');
var center = { top: slider.offset().top, left: slider.offset().left + slider.width() / 2 };
var offset = slider.offset();
function calculateTopLeft(angle) {
var radius = slider.width() / 2,
radians = (angle * Math.PI) / 180;
pointer.css({
left: center.left + radius * Math.cos(radians),
top: center.top + radius * Math.sin(radians)
});
}
//Equation of the circle
//x = a + r * cos(t);
//y = b + r * sin(t);​
And here is an example: http://jsfiddle.net/zFRwM/2/
Probably you'll need a little correction but I think that the idea is clear.
use this in your javascript
function getPosition(obj){
var topValue= 0,leftValue= 0;
while(obj){
leftValue+= obj.offsetLeft;
topValue+= obj.offsetTop;
obj= obj.offsetParent;
}
finalvalue = leftValue + "," + topValue;
return finalvalue;
}
var d = document.getElementById('divname');
getPosition(d);
Then try this,it use .position() function in jquery use this
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
var p = $("div");
var position = p.position();
$("div").text( "Right: " + position.right + ", top: " + position.top );
</script>
Remove transform, retrieve offset, put transform back:
$.fn.offsetNoTransform = function(e)
{
var m = this.css('transform');
this.css('transform', '');
var off = this.offset();
this.css('transform', m);
return off;
}

Categories