Get live position of two div and update connecting line - javascript

I've recently followed this example but I'm struggling to get the live position of div's and updating the connecting line with the relevant position.
Lines connecting to responsive elements
Example of my work here
https://jsfiddle.net/spencer1997/vktg31e2/24/
How to draw a line between two divs
Need it to be something like this :
$('.btn').animate({ 'margin-left':'200px', 'margin-top':'70px'}, 3000)
setInterval(function(){
var div = $('.btn').offset();
$( ".live-position" ).text( "left: " + div.left + ", top: " + div.top );
}, 100);
https://jsfiddle.net/rpgpp2mp/
Any help will be greatly appreciated.

this shall do the trick, it relies on maths essentially, if you want to change teh position either of the line or the text, you have to change the top and left value so that the angle is still valid and add an offset top and left
$('.btn').animate({ 'margin-left':'200px', 'margin-top':'70px'}, 3000)
const int = setInterval(function(){
const btn = $('.btn').offset();
$( ".live-position" ).text( "left: " + btn.left + ", top: " + btn.top );
const line = document.getElementById("line")
const angle = Math.atan(btn.top / btn.left);
line.style.transform = `rotateZ(${angle}rad)`;
line.style.width=`${Math.sqrt(Math.pow(btn.top, 2)+Math.pow(btn.left, 2))}px`
}, 100);
setTimeout(() => clearInterval(int), 3000)
#line {
display: block;
background-color: red;
height: 2px;
width: 5em;
transform-origin: top left;
position: absolute;
top: 0;
left: 0;
}
.btn {
top: 0;
left: 0;
position: absolute;
}
<div>position: <p class="live-position"></p></div>
<div class="btn">text</div>
<span id="line"></span>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Related

Cant get offset of div

this is my getoffset js code to get div width and left
var objRedPacketDivStyle = document.getElementById("styRedPacketAppear");
var objOffset = objRedPacketDivStyle.offset();
var intWidth = objOffset.offsetWidth;
var objWidthStart = objOffset.offset.left;
var objWidthEnd = objWidthStart + intWidth;
alert(objWidthStart + objWidthEnd);
and here is my div and css
<div class="styRedPacketAppear" id="styRedPacketAppear"></div>
#styRedPacketAppear {
position: fixed;
top: 0;
left: 0;
width: 100%;
z-index: 98;
pointer-events: none;
}
This isn't working as .offset() is a jQuery method. Since you don't have jquery you need to use vanilla javascript to achieve this.
You can use:
element.offsetWidth: "returns the layout width of an element as an integer." - MDN
element.offsetLeft: "returns the number of pixels that the upper left corner of the current element is offset to the left within the HTMLElement.offsetParent node." - MDN
Using these two properties will resolve your issue:
var objRedPacketDivStyle = document.getElementById("styRedPacketAppear");
// Remove this: var objOffset = objRedPacketDivStyle.position.offset();
var intWidth = objRedPacketDivStyle.offsetWidth;
var objWidthStart = objRedPacketDivStyle.offsetLeft;
var objWidthEnd = objWidthStart + intWidth;
alert(objWidthStart + objWidthEnd);
#styRedPacketAppear {
position: fixed;
top: 0;
left: 0;
width: 100%;
z-index: 98;
pointer-events: none;
}
<div class="styRedPacketAppear" id="styRedPacketAppear"></div>
The offsetTop property returns the top position (in pixels) relative to the top of the offsetParent element.
The returned value includes:
-the top position, and margin of the element
-the top padding, scrollbar and border of the offsetParent element.
#test {
top: 100px;
margin: 10px;
padding: 10px;
width: 300px;
position: fixed;
border: 5px solid black
}
var testDiv = document.getElementById("test");
document.getElementById("demo").innerHTML = testDiv.offsetTop;
Result-offsetTop is: 110

Spawn blocks at random locations

I'm trying to create elements in random locations on the screen but I have run into some trouble. Creating the elements works but when I try to make them have random locations, nothing happens. Thanks for the help in advance.
Here's my code:
var newObject = document.createElement("DIV");
newObject.setAttribute("class", "object");
newObject.setAttribute("id", "powerup");
document.body.appendChild(newObject);
var powerup = document.getElementById("powerup");
var object = document.getElementsByClassName("object");
for (i = 0; i < object.length; i++) {
object[i].style.top = Math.floor(Math.random() * window.innerHeight) + 50 + "px";
object[i].style.left = Math.floor(Math.random() * window.innerWidth) + 50 + "px";
}
function createObject() {
var newObject = document.createElement("DIV");
newObject.setAttribute("class", "object");
newObject.setAttribute("id", "powerup");
document.body.appendChild(newObject);
for (i = 0; i < object.length; i++) {
object[i].style.top = Math.floor(Math.random() * window.innerHeight) + 50 + "px";
object[i].style.left = Math.floor(Math.random() * window.innerWidth) + 50 + "px";
}
}
html, body {
height: 100%;
width: 100%;
margin: 0;
}
#powerup {
background: red;
height: 10px;
width: 10px;
}
<body>
<button onclick="createObject()">Create a Block</button>
</body>
Your code is working correctly. Its able to set top and left of each #powerup element. The only problem is that the position of #powerup is static by default. So you just need to change css of #powerup element to
#powerup {
background: red;
height: 10px;
width: 10px;
position: relative;
}
position: absolute can also be used. Choose the one that fits your requirements.
I made a CodePen with your code.
For those elements to have their top and left properties have an effect, you need to add position: absolute; to the #powerup elements.
#powerup {
background: red;
height: 10px;
width: 10px;
position: absolute;
}
Also, I'm not sure if this is what you intended, but your JavaScript code is selecting a new random location for each pre-existing #powerup element whenever you click the button.

Stick a div underneath thumbnails + limit the width

Alright. This might sound a little bit complicated. I've got a script which fetches thumbnails from a JSON. It fetches 9 thumbnails and onclick of the #load it fetches 9 more. How can I set the Load more button underneath the thumbnails and how to make it stick to the bottom of them each time you click it? ( I do not want it like it's now, on the side, but right in the middle and underneath them ).
+BONUS question: How can I fixate the thumbnails so they always show up 3 in a row. Since now, when I resize the window they change ( as you can see in the fiddle, there's only 2 per row now ).
jsfiddle.net/z6ge55ky/
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<div id="twitch">
<script src="js/main.js"></script>
<div id="load">
<img class="hvr-pulse" src="http://i.imgur.com/KHIYHFz.png?1">
</div>
</div>
$(function() {
var i=0;
var twitchApi = "https://api.twitch.tv/kraken/streams";
var twitchData;
$.getJSON(twitchApi, function(json) {
twitchData = json.streams;
setData()
});
function setData(){
var j = twitchData.length > (i + 9) ? (i + 9) : twitchData.length;
for (; i < j; i++) {
var streamGame = twitchData[i].game;
var streamThumb = twitchData[i].preview.medium;
var streamVideo = twitchData[i].channel.name;
var img = $('<img style="width: 250px; height: 250px;" src="' + streamThumb + '"/>')
$('#twitch').append(img);
img.click(function(){
$('#twitch iframe').remove()
$('#twitchframe').append( '<iframe frameborder="0" style="overflow:hidden; margin-left: 25px; width:400px; height:250px; position: fixed; top: 0; margin-top: 23.55%;" src="http://player.twitch.tv/?channel=' + streamVideo + '"></iframe>');
});
}
}
$('#load').click(function() {
setData();
});
});
#twitch {
width: 60%;
position: absolute;
left: 20%;
text-align: center;
}
#twitch img {
border: 5px solid rgba(0,0,0,0);
margin: 0 auto;
cursor: pointer;
}
#load {
bottom: 0;
position: absolute;
}
You have declared the width for #twitch 60% remove that and for #load use top:100%
DEMO on jsfiddle

How to move a carousel item to the middle when it's clicked in jquery

How can I make the carousel center the item I've clicked to the middle? I've looked everywhere for an answer but they're not straight answers... Can someone help me in this, please?
This is what I've done so far: http://jsfiddle.net/sp9Jv/
HTML:
<div id="wrapper">
<div id="carousel">
prev
next
<div class="viewport">
<ul>
<li>Un</li>
<li>Deux</li>
<li>Trois</li>
<li>Quatre</li>
<li>Cinq</li>
<li>Six</li>
<li>Sept</li>
<li>Huit</li>
</ul>
</div>
<!-- viewport -->
</div>
<!-- carousel -->
</div>
<!-- wrapper -->
JavaScript:
var carousel = $('#carousel'),
prev = carousel.find('.prev'),
next = carousel.find('.next'),
viewport = carousel.find('.viewport'),
item = viewport.find('li'),
itemWidth = item.outerWidth(true),
itemNum = item.length,
itemList = viewport.find('ul');
itemList.width(itemWidth * itemNum);
var moveCarousel = function(dir) {
itemList.animate({ left: '-=' + (itemWidth * dir) + 'px' }, 400);
};
//prev
prev.on('click', function(e) {
e.preventDefault();
moveCarousel(-1);
});
//next
next.on('click', function(e) {
e.preventDefault();
moveCarousel(1);
});
//carousel item
item.on('click', 'a', function(e) {
var self = $(this),
selfIndex = self.index(),
distance = itemList.width() / 2,
selfPos = self.position(),
selfPosLeft = selfPos.left,
viewportPosLeft = viewport.position().left;
e.preventDefault();
//move item to middle, but it doesn't work...
if (selfPosLeft > Math.floor(viewport.width())/3) {
itemList.animate({ left: '-' + Math.floor(viewport.width())/3 + 'px' }, 400);
}
if (selfPosLeft < Math.floor(viewport.width())/3) {
itemList.animate({ left: Math.floor(viewport.width())/3 + 'px' }, 400);
}
});
CSS:
#wrapper {
width: 500px;
margin: 20px auto;
}
#carousel {
position: relative;
}
.viewport {
width: 260px;
border: 1px solid #6e6e6e;
height: 80px;
overflow: hidden;
position: relative;
margin-left: 100px;
}
.prev, .next {
position: absolute;
}
.prev {
top: 20px;
left: 0;
}
.next {
top: 20px;
right: 0;
}
.viewport ul {
position: absolute;
}
.viewport li {
float: left;
margin-right: 10px;
}
.viewport li a {
display: block;
width: 80px;
height: 80px;
background: #ddd;
}
While you have prepared all the information needed about all items, you can calculate the value of the left based on the clicked item.
Here is my modification:
and I've bound the click action of carousel items with this function and passed the clicked item using the self keyword.
var itemClicked=function(item){
var itemIndex=$(item).index(),
newLeft=(itemIndex*itemWidth*-1)+Math.floor(($(viewport).width()/itemWidth)/2)*itemWidth;
$(itemList).animate({left:newLeft+"px"},400);
};
You can check it working on this url: http://jsfiddle.net/rUZHg/3/
I assume that this should work despite of the number of viewed elements while it calculates the padding between the left 0 and the left of the center element.
Alright, it's ugly, I hope it gives you some ideas.
I created a global currentItem that tracks what's in the center. Every time the carousel moves this is updated.
The very useful variable I found was selfPosLeft which told me what was being clicked. I should add that 90 was the multiple I got from clicking around. Must be linked to your CSS and I don't know how to find this number dynamically.
Please try it :) http://jsfiddle.net/sp9Jv/4/
Well, I'm picturing that when you have more than 3 items you can change the code to compute the difference between the current item and the selfPosLeft of the clicked one, I'll leave that to you :) Like this, seems to work. http://jsfiddle.net/sp9Jv/5/

Simple way to show a message bar at the top of a page

I would like to implement something like stackoverflow does, the bar at top of the page that shows some message.
I came across this pretty nice effect with a page bounce too:
http://www.slidedeck.com/features/ (look at the purple top bar coming down)
Is there a simple way to do this? Maybe with only jQuery or other framework?
How about this? :)
Just add some fancy graphics and it should be good to go!
I just found a great and simple solution From blog.grio.com
jsFiddle Demo
function showNotificationBar(message, duration, bgColor, txtColor, height) {
/*set default values*/
duration = typeof duration !== 'undefined' ? duration : 1500;
bgColor = typeof bgColor !== 'undefined' ? bgColor : "#F4E0E1";
txtColor = typeof txtColor !== 'undefined' ? txtColor : "#A42732";
height = typeof height !== 'undefined' ? height : 40;
/*create the notification bar div if it doesn't exist*/
if ($('#notification-bar').size() == 0) {
var HTMLmessage = "<div class='notification-message' style='text-align:center; line-height: " + height + "px;'> " + message + " </div>";
$('body').prepend("<div id='notification-bar' style='display:none; width:100%; height:" + height + "px; background-color: " + bgColor + "; position: fixed; z-index: 100; color: " + txtColor + ";border-bottom: 1px solid " + txtColor + ";'>" + HTMLmessage + "</div>");
}
/*animate the bar*/
$('#notification-bar').slideDown(function() {
setTimeout(function() {
$('#notification-bar').slideUp(function() {});
}, duration);
});
}
var _show = true;
$(document).ready(function() {
$('button#showHide')
.bind('click', function() {
if (_show) {
$('div#hideMe')
.animate({
'height': '25px'
}, 750);
_show = false;
} else {
$('div#hideMe')
.animate({
'height': '0px'
}, 750);
_show = true;
}
});
});
body {
background-color: #003366;
padding: 0px;
margin: 0px;
text-align: center;
}
button {
cursor: pointer;
right: 5px;
float: right;
position: relative;
top: 5px;
}
div#hideMe {
background-color: #FF3399;
height: 0px;
overflow: hidden;
position: relative;
}
div#container {
background-color: #FFFFFF;
border: #FFFF00 1px solid;
height: 600px;
margin-left: auto;
margin-right: auto;
overflow: hidden;
position: relative;
}
div#contents {
height: 600px;
position: absolute;
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="hideMe">Congratulations, you just won a punch in the neck!</div>
<div id="container">
<div id="contents">
<button id="showHide">clicker</button>
</div>
</div>
Was just playing around with this. Does about what your example did. :)
you could do this about 17,334,259 different ways. But this'll work. Just make sure your boxes are positioned relatively, so the expansion of #hideMe pushes #container down too. Or absolutely position it and fix it to 0px,0px. or whatever...
You'll need to fetch the message to display, possibly via Ajax, but:
http://jsfiddle.net/ZpBa8/4/
shows how to show a bar across the top in jQuery and is a start
The same people who make the plugin whose page you love make a plugin to do what you love about it: http://www.hellobar.com/
The Meerkat jQuery plugin does this very nicely.
This can easily be done without jquery even. Just use the DOM to append a div element to the body and set its top position to zero. Set its width as the screen.width and height to be lets say 50px. And just initiate an opacity fade in/fade out. Like the following sample. This sample is for IE. Read this for reference. Call initFade to being the Fade In and Fade out process.
var OP = 90;
function processFade() {
var t = "";
OP = OP - 3;
if (OP < 0) {
clearTimeout(t);
OP = 90;
return;
}
$("YOUR_DIV_ELEMENT_HERE").style.filter = "alpha(opacity=" + OP + ")";
if (OP == 0) {
$("YOUR_DIV_ELEMENT_HERE").style.display = "none";
clearTimeout(t);
OP = 90;
return;
}
t = setTimeout("processFade();", 100);
}
function initFade() {
processFade();
}

Categories