call onmousedown and onclick using this inside a custom class with JS - javascript

I want to make circle(army) with move when I drag it and when I click it, it should not move but do something else.
fucntion unit() {
this.circle = document.createElementNS(svgNs, "circle");
//Some attributes are added to this.circle
document.getElementById("svg1").appendChild(this.circle);
this.moving = false;
this.circle.onclick = function () {
showForm(this);
}
this.circle.onmousedown = function () {
this.moving = true;
}
}

Alright, I know that you didn't tag jQuery in your code, but if you have looked at my other posts, I tend to go full jQuery. If you wanted to do this, do this:
let's say this applies to your circle id element:
$("#circle").draggable( 'enable' )
var isDragging = 0;
var isUp = 1;
$("#circle").mousedown(function() {
isDragging = 0;
isUp = 0;
})
$("#circle").mousemove(function() {
isDragging = 1;
});
$("#circle").mouseup(function() {
isDragging = 0;
isUp = 1;
});
$("#circle").mousedown(function() {
if (isUp == 1) {
//click function
} else if (isDragging == 1) {
//drag function
}
});
This might be a little buggy, but I tried.

Related

Issues with making images draggable

I am currently creating my own website. I need code to allow users to change the position of some images by dragging them. I have written this HTML, CSS and JS in separate files.
The whole click and drag think works, when I click on the image and drag it on any side, it moves.
When I release the mouse button nothing happens. I have tried break and return, but they don't stop the function. Do you have any suggestions?
PS: I'm only a beginner in JS, so if you have any other advice about my code, go for it!
class img {
constructor(id, left, top) {
this.id = "#" + id;
this.left = parseInt(left, 10);
this.top = parseInt(top, 10);
};
};
$(".draggable").on("mousedown", function detectClick(focus) {
var stop = false;
var clickPos = [focus.pageX, focus.pageY];
var selected = new img($(this).attr('id'), $(this).css("left"), $(this).css("top"));
console.log(clickPos, selected);
$(selected.id).on("mousemove", function startMvt(move) {
var newPos = [move.pageX, move.pageY];
console.log(newPos);
$(selected.id).css("top", selected.top + newPos[1] - clickPos[1]);
$(selected.id).css("left", selected.left + newPos[0] - clickPos[0]);
$(selected.id).on("mouseup", function stop() {
var stop = true
console.log("stopped moving!");
return;
});
if (stop) {
return false;
};
});
if (stop) {
return false;
};
}).delay(5);
.draggable {
position: relative;
}
#img_1 {
top: 10%;
left: 20%;
z-index: 1;
cursor: move;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img class="draggable" id="img_1" draggable="false" src="content/medium_im_test.jpg">
$(".draggable").on("mousedown",
you are only calling a function on the event of mousedown, you need a corresponding mouseup event handler.
how about adding
.mouseup(function(){
alert('up');
});
at the end or .delay(5);
like
$(".draggable").on("mousedown", function detectClick(focus) {
var stop = false;
var clickPos = [focus.pageX, focus.pageY];
var selected = new img($(this).attr('id'), $(this).css("left"), $(this).css("top"));
console.log(clickPos, selected);
$(selected.id).on("mousemove", function startMvt(move) {
var newPos = [move.pageX, move.pageY];
console.log(newPos);
$(selected.id).css("top", selected.top + newPos[1] - clickPos[1]);
$(selected.id).css("left", selected.left + newPos[0] - clickPos[0]);
$(selected.id).on("mouseup", function stop() {
var stop = true
console.log("stopped moving!");
return;
});
if (stop) {
return false;
};
});
if (stop) {
return false;
};
}).delay(5).mouseup(function(){
alert('up');
});
it worked for me!! I am also a beginner js programmer! so I don't fully understand your code, but I think you have to do something where I put alert('up')

svgjs how to replay and control series of animations using slider

I am using svg.js and would like to play a series of animations and then provide a slider for the user to control the animation to look at it more closely. It looks like when an animation is complete, svg.js cleans up the resources so the situation gets nulled out so I can't reset it. I have a fiddle with a simplified example. After the animation plays once, I would like to then be able to use the slider and use the at method to reposition the animations.
https://jsfiddle.net/voam/xeajbhea/2/
var draw = SVG('drawing'),
rectA1 = draw.rect(50, 50).fill('#f06'),
rectA2 = draw.rect(50, 50).fill('#60f').translate(200),
rectB1 = draw.rect(50, 50).fill('#ce0').translate(0, 100).opacity(0),
rectB2 = draw.rect(50, 50).fill('#0ec').translate(200, 100).opacity(0);
var animation1 = rectA1.animate().move(200).opacity(0);
var animation2 = rectA2.animate().move(-200).opacity(0).during(function(pos) {
document.getElementById("range_animation").value = pos;
});
var animation3, animation4;
animation2.after(function(situation) {
animation3 = rectB1.animate().move(200).opacity(1);
animation4 = rectB2.animate().opacity(1).move(-200)
.during(function(pos) {
document.getElementById("range_animation").value = 1 + pos;
});
console.log('animations', animation1, animation2, animation3, animation4);
});
document.getElementById("range_animation").addEventListener("change", function(el) {
///console.log('change', el, );
var val = this.value;
if (animation1.situation) {
if (val < 1) {
animation1.at(val).pause();
animation2.at(val).pause();
} else {
animation3.at(val - 1).pause();
animation4.at(val - 1).pause();
}
}
}, false);
HTML below:
<div id="drawing">
</div>
<input type="range" id="range_animation" min="0.01" max="2" step=".01" value=".01">
One approach that works is as #Fuzzyma mentioned is to make the animations loop so they don't get terminated. Then one has to manage the transition sets from one to another. Any animations that don't get run immediately start in a paused state. In my real project not this demo there are 5 animation sets each with subanimations so lets see if this turns out to be manageable!
var atEnd = function (pos) {
var rounded = pos.toFixed(2);
return (rounded == .99 || rounded == 1.00);
};
var draw = SVG('drawing')
, rectA1 = draw.rect(50, 50).fill('#f06')
, rectA2= draw.rect(50, 50).fill('#60f').translate(200)
, rectB1 = draw.rect(50, 50).fill('#ce0').translate(0, 100).opacity(0)
, rectB2 = draw.rect(50, 50).fill('#0ec').translate(200, 100).opacity(0);
var animation3, animation4, lastTotalRange;
var animation1 = rectA1.animate().move(200).opacity(0).loop();
var animation2 = rectA2.animate().move(-200).opacity(0).loop();
animation2
.during(function( pos ) {
document.getElementById("range_animation").value = pos;
if ( atEnd (pos) ) {
animation2.pause();
animation3 = rectB1.animate().move(200).opacity(1).loop();
animation4 = rectB2.animate().opacity(1).move(-200).loop();
animation4
.during(function( pos ) {
if (pos > 0) {
document.getElementById("range_animation").value = 1 + pos;
}
if (atEnd (pos)) {
animation4.pause();
}
});
animation3.during( function(pos) {
if (atEnd (pos)) {
animation3.pause();
}
});
}
});
animation1.during(function( pos ) {
if (atEnd (pos)) {
animation1.pause();
}
});
$('input#range_animation').on('input', function() {
$(this).trigger('change');
})
$('input#range_animation').on('change', function() {
var val = $( this).val(),
delta = 0;
if (lastTotalRange) {
delta = val - lastTotalRange;
}
if (val < 1) {
animation1.at(val).pause();
animation2.at(val).pause();
if (lastTotalRange > 1) {
animation3.at(.01);
animation4.at(.01);
}
}
else {
animation3.at(val - 1).pause();
animation4.at(val - 1).pause();
if (lastTotalRange < 1) {
animation1.at(.99);
animation1.at(.99);
}
}
// console.log('totalAnimationRange:change', delta, val);
lastTotalRange = val;
})
and the html
<div id="drawing"></div>
<input type="range" id="range_animation" min="0.00" max="1.99" step=".01" value=".01">
and the jsfiddle:
jsfiddle.net/voam/ob2bjfur/1/

JavaScript function dosen't work correct

I have a function that checking board is there a searching element.
First script creating a board with different elements. Element in the square next to board is element that user has to find on the board and click them.
User has to click (as quick as possible) all searching elements. After click on element function checking a board, is there more elements. If yes then nothing happen and user has to click another one. If on board there isn’t searching elements then function display a time and new board create.
But some reason function works correct only first time after page load. Latter function ignore more then one element on board or see element that doesn’t exist on board any more.
Can you tell me what is wrong.
Part of code bellow and there is a link to testing page.
http://doomini2.linuxpl.info/font/
Thank you
function secondStage() {
createBoxes(59);
var usingSet = [];
var i = 0;
var boxList = document.querySelectorAll("#board > div");
createSet(usingSet, 20, shapes);
(function paint() {
if (i <= 59) {
var curentBox = boxList[i];
curentBox.className = usingSet[draw(20)];
curentBox.style.color = colors[draw(colors.length - 5)];
timeStop = setTimeout(paint, 50);
i++;
} else {
var findShape = boxList[draw(59)];
toFind.className = findShape.className;
toFind.style.color = findShape.style.color;
findBoxes(boxList);
clearTimeout(timeStop);
}
})();
}
//function checks boxes to find a proper shape
function findBoxes(boxList) {
startTime = Date.now();
board.addEventListener("mousedown", function (e) {
if ((e.target.className === toFind.className)) {
e.target.className = "correct";
e.target.innerHTML = "OK";
checkBoard();
} else if (e.target.id === "board" || e.target.className === "correct") {
} else {
e.target.className = "false";
e.target.innerHTML = "NO";
}
}, false);
function checkBoard() {
var condition = false;
console.log(condition);
for (var x = 0; x < boxList.length; x++) {
if ((boxList[x].className === toFind.className)) {
condition = true;
console.log(condition);
}
}
if (condition === false) {
var clickTime = Date.now();
var timeResult = parseFloat(((clickTime - startTime) / 1000).toFixed(3));
lastResult.innerHTML = timeResult + "s";
secondResult[secondResult.length] = timeResult;
console.log(secondResult);
displayResult(secondStage);
}
}
}
//function displaig results after every single round
function displayResult(stage) {
cover.className = "";
TweenMax.to("#lastResultDiv", 1, {ease: Back.easeOut, right: (winWidth / 4), });
TweenMax.to("#go", 1, {ease: Back.easeOut, top: (winWidth / 3), onComplete: function () {
goButton.addEventListener("click", function () {
clear();
}, false);
}});
//clear board and return to play
function clear() {
TweenMax.to("#lastResultDiv", 1, {ease: Back.easeIn, right: winWidth, });
TweenMax.to("#go", 1, {ease: Back.easeOut, top: -100, onComplete: function () {
cover.className = "hide";
lastResultDiv.style.right = "-592px";
toFind.className = "";
board.innerHTML = "";
if (firstStageRound === 10) {
secondStage();
} else if (secondStageRound === 5) {
thirdStage();
} else {
stage();
}
}});
}
}
Not Load this File http://cdnjs.cloudflare.com/ajax/libs/gsap/1.17.0/TweenMax.min.js
try to local path

How to make expand all/collapse all button in this certain script?

i would like to ask for help in a simple task i really need to do at my work (I am a javascript newbie). I made a simple collapsible list with script provided by this guy http://code.stephenmorley.org/javascript/collapsible-lists/ but what i need right now are two simple buttons as stated in the title: expand all and collapse whole list. Do you guys know if something like that can be implemented in this certain script? Please help :)
var CollapsibleLists = new function () {
this.apply = function (_1) {
var _2 = document.getElementsByTagName("ul");
for (var _3 = 0; _3 < _2.length; _3++) {
if (_2[_3].className.match(/(^| )collapsibleList( |$)/)) {
this.applyTo(_2[_3], true);
if (!_1) {
var _4 = _2[_3].getElementsByTagName("ul");
for (var _5 = 0; _5 < _4.length; _5++) {
_4[_5].className += " collapsibleList";
}
}
}
}
};
this.applyTo = function (_6, _7) {
var _8 = _6.getElementsByTagName("li");
for (var _9 = 0; _9 < _8.length; _9++) {
if (!_7 || _6 == _8[_9].parentNode) {
if (_8[_9].addEventListener) {
_8[_9].addEventListener("mousedown", function (e) {
e.preventDefault();
}, false);
} else {
_8[_9].attachEvent("onselectstart", function () {
event.returnValue = false;
});
}
if (_8[_9].addEventListener) {
_8[_9].addEventListener("click", _a(_8[_9]), false);
} else {
_8[_9].attachEvent("onclick", _a(_8[_9]));
}
_b(_8[_9]);
}
}
};
function _a(_c) {
return function (e) {
if (!e) {
e = window.event;
}
var _d = (e.target ? e.target : e.srcElement);
while (_d.nodeName != "LI") {
_d = _d.parentNode;
}
if (_d == _c) {
_b(_c);
}
};
};
function _b(_e) {
var _f = _e.className.match(/(^| )collapsibleListClosed( |$)/);
var uls = _e.getElementsByTagName("ul");
for (var _10 = 0; _10 < uls.length; _10++) {
var li = uls[_10];
while (li.nodeName != "LI") {
li = li.parentNode;
}
if (li == _e) {
uls[_10].style.display = (_f ? "block" : "none");
}
}
_e.className = _e.className.replace(/(^| )collapsibleList(Open|Closed)( |$)/, "");
if (uls.length > 0) {
_e.className += " collapsibleList" + (_f ? "Open" : "Closed");
}
};
}();
It is important to understand why a post-order traversal is used. If you were to just iterate through from the first collapsible list li, it's 'children' may (will) change when expanded/collapsed, causing them to be undefined when you go to click() them.
In your .html
<head>
...
<script>
function listExpansion() {
var element = document.getElementById('listHeader');
if (element.innerText == 'Expand All') {
element.innerHTML = 'Collapse All';
CollapsibleLists.collapse(false);
} else {
element.innerHTML = 'Expand All';
CollapsibleLists.collapse(true);
}
}
</script>
...
</head>
<body>
<div class="header" id="listHeader" onClick="listExpansion()">Expand All</div>
<div class="content">
<ul class="collapsibleList" id="hubList"></ul>
</div>
</body>
In your collapsibleLists.js
var CollapsibleLists =
new function(){
...
// Post-order traversal of the collapsible list(s)
// if collapse is true, then all list items implode, else they explode.
this.collapse = function(collapse){
// find all elements with class collapsibleList(Open|Closed) and click them
var elements = document.getElementsByClassName('collapsibleList' + (collapse ? 'Open' : 'Closed'));
for (var i = elements.length; i--;) {
elements[i].click();
}
};
...
}();

Js and Divs, (even <div> is difference)

I Have find a javascript code that works perfectly for showing a DIV.
but this code works only for showing one div for each page.
i want to include many DIVS for hiding and showing in the same page.
I was try to replace the div id and show/hide span id with a rundom php number for each include, but still is not working.
so how i have to do it?
the JS code:
var done = true,
fading_div = document.getElementById('fading_div'),
fade_in_button = document.getElementById('fade_in'),
fade_out_button = document.getElementById('fade_out');
function function_opacity(opacity_value) {
fading_div.style.opacity = opacity_value / 100;
fading_div.style.filter = 'alpha(opacity=' + opacity_value + ')';
}
function function_fade_out(opacity_value) {
function_opacity(opacity_value);
if (opacity_value == 1) {
fading_div.style.display = 'none';
done = true;
}
}
function function_fade_in(opacity_value) {
function_opacity(opacity_value);
if (opacity_value == 1) {
fading_div.style.display = 'block';
}
if (opacity_value == 100) {
done = true;
}
}
// fade in button
fade_in_button.onclick = function () {
if (done && fading_div.style.opacity !== '1') {
done = false;
for (var i = 1; i <= 100; i++) {
setTimeout((function (x) {
return function () {
function_fade_in(x)
};
})(i), i * 10);
}
}
};
// fade out button
fade_out_button.onclick = function () {
if (done && fading_div.style.opacity !== '0') {
done = false;
for (var i = 1; i <= 100; i++) {
setTimeout((function (x) {
return function () {
function_fade_out(x)
};
})(100 - i), i * 10);
}
}
};
Check out the Fiddle, you can edit code based on your needs ;)
$(function() {
$('.sub-nav li a').each(function() {
$(this).click(function() {
var category = $(this).data('cat');
$('.'+category).addClass('active').siblings('div').removeClass('active');
});
});
});
finaly i found my self:
<a class="showhide">AAA</a>
<div>show me / hide me</div>
<a class="showhide">BBB</a>
<div>show me / hide me</div>
js
$('.showhide').click(function(e) {
$(this).next().slideToggle();
e.preventDefault(); // Stop navigation
});
$('div').hide();
Am just posting this in case someone was trying to answer.

Categories