x and y position finder JQuery JS - javascript

I have a script that should find the x and y position. I can find the x position without any problem but my y position appears to be infinity, and i can not figure out why. here is my script
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script language"javascript" type"text/javascript">
$(document).ready(function(){
$(".view_parent_furnace_boiler").droppable();
});
$(document).ready(function() {
$(".device-container").draggable(
{
grid: [10, 10],
containment: "#picture_container",
revert: 'invalid',
stop: function(){
($(".door").height() / 100)+"%");
var elementName = $(this).attr('name');
console.log(elementName);
var elementID = $(this).attr('id');
elementID = elementID.split(",");
var parent = $(this).parent();
/*finding the x and y position percentage based on the container*/
var yPosition = parseInt($(this).css('top'))/parent.height()*100;
var xPosition = parseInt($(this).css('left'))/parent.width()*100;
console.log(xPosition); //displays without anyproblem
console.log(yPosition); //does not work (infinity
/*assigning the div id to variable for further display and debugging purpose*/
for (var k = 0; k < elementID.length; k++) {
var device_id = elementID[0];
var command = elementID[1];
var map_id = elementID[2];
}
/*assigining values to variables*/
$('#'+elementName+'-device_id').val(device_id);
$('#'+elementName+'-command').val(command);
$('#'+elementName+'-map_id').val(map_id);
$('#'+elementName+'-x_position').val(xPosition);
$('#'+elementName+'-y_position').val(yPosition);
},
revert: 'invalid'
});
});
</script>
here is my css
<style type="text/css">
/* to display the boiler background picture*/
.view_parent_furnace_boiler {
position: relative;
background-position: relative;
max-width: 100%;
max-height: 100%;
padding: 0em;
margin: 0em;
border-image-width: 5% 2em 10% auto;
border: 3px solid #ccc;
background:radial-gradient(circle, black, white);
}
.view_parent_furnace_boiler img {
max-width: auto;
max-height: auto;
}
.view_parent_furnace_boiler span {
color: #000;
}
.btn-inhibited{
background-color:#aaa;
color:white;
}
.device-container {
position: absolute; /*could be relative*/
cursor: move;
}
</style>

Try using jQuery $(this).offset().top or $(this).position().top instead of $(this).css('top').
https://api.jquery.com/position/
https://api.jquery.com/offset/

I tried this var yPosition = parseInt($(this).css('top'))/parent.weight()*200; and it worked perfectly, now i can find my height 100% without any problem.

Related

jQuery hover is too slow

Please run the snippet and drag you mouse over the bar to make it red.
If you drag the mouse very slowly, you will fill it red, but if you move it fast, there will be white holes in it.
How to fix it? (the white holes)
I want to make a bar divided into 500 parts and if you hover it, it becomes red and being able to drag fast and fill it without holes.
Any help appreciated :)
$(function() {
var line = $("#line");
for ( var i = 0; i < 500; i++) {
line.append('<div class="tile" id="t'+(i+1)+'"></div>');
}
var tile = $(".tile");
tile.hover (
function() { //hover-in
$(this).css("background-color","red");
},
function() { //hover-out
}
);
});
#line{
height: 50px;
background-color: #000;
width: 500px;
}
.tile {
height: 50px;
float: left;
background-color: #ddd;
width: 1px;
}
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<div id="line"></div>
With your design one way would be to iterate over the first to your current hovered element and fill it, which would lead no spaces. That said you may want to consider using the HTML5 Canvas and drawing a rectangle from 0 to your mouse position, which will perform significantly faster.
$(function() {
var line = $("#line");
for ( var i = 0; i < 500; i++) {
line.append('<div class="tile" id="t'+(i+1)+'"></div>');
}
var tile = $(".tile");
tile.hover (
function() { //hover-in
var self = this;
$("#line").children().each(function(){
$(this).css("background-color","red");
if(this == self) return false;
});
},
function() { //hover-out
}
);
});
#line{
height: 50px;
background-color: #000;
width: 500px;
}
.tile {
height: 50px;
float: left;
background-color: #ddd;
width: 1px;
}
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<div id="line"></div>
Edit
Below is an example doing the same task but using the HTML 5 Canvas:
$("#line").mousemove(function(e){
var canvas = $(this)[0];
var ctx = canvas.getContext("2d");
var rect = canvas.getBoundingClientRect()
var x = e.clientX - rect.left;
ctx.fillStyle="red";
ctx.fillRect(0, 0, x, canvas.height);
});
#line{ background-color: #ddd; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="line" width=500 height=50 ></canvas>
This is another approach with nextUntil to select siblings..
$(function() {
var line = $("#line");
for ( var i = 0; i < 500; i++) {
line.append('<div class="tile" id="t'+(i+1)+'"></div>');
}
var tile = $(".tile");
line.on( 'mouseover', function(ev){
$('.tile').first().nextUntil( $('.tile').eq(ev.pageX) ).css("background-color","red");
});
line.on( 'mouseleave', function(ev){
$('.tile').css("background-color","#ddd");
});
});
#line{
height: 50px;
background-color: #000;
width: 500px;
}
.tile {
height: 50px;
float: left;
background-color: #ddd;
width: 1px;
}
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<div id="line"></div>
Another solution makes use of jQuery's mousemove method. This allows the bar to go both forward and backwards, simply following the cursors position.
This detects movement inside of the div, then I calculate the position of the cursor within the div as a percentage and apply it as the width of the red bar.
$( ".bar" ).mousemove(function( event ) {
var xCord = event.pageX;
xPercent = (xCord + $('.pct').width()) / $( document ).width() * 100;
$('.pct').width(xPercent+'%');
});
.bar{
background:'#999999';
width:50%;
height:50px;
}
.pct{
height:100%;
background:red;
width:0%;
}
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js">
</script>
<div class="bar" style="background:#999999">
<div class="pct"></div>
</div>

Function to count number of line breaks acts differently on $(window).on('resize') and $(document).ready

I have a function which counts the number of line breaks in a div, depending on the width of the window. While the functions works fine when placed in the $(window).on('resize') function, it does not work when put in $(document).ready() function. I want it to work right on page load, and also window resize, how do I support both?
JSFiddle
Javascript/jQuery:
// functions called in both document.ready() and window.resize
$(document).ready(function(){
var lineCount = getLineCount();
postItems(lineCount);
$('.answer').text("Ready");
});
$(window).on('resize', function(){
var lineCount = getLineCount();
postItems(lineCount);
$('.answer').text("Number of lines: " + lineCount);
});
// calculates the amount of lines required to hold the items
function getLineCount() {
var lineWidth = $('.line').width();
var itemWidthSum = 0;
var lineCount=1;
$('.item').each(function(index, element) {
if((lineWidth - itemWidthSum) > ($(element).outerWidth())) {
itemWidthSum = itemWidthSum + $(element).outerWidth();
} else {
lineCount++;
itemWidthSum = $(element).outerWidth();
}
});
return lineCount;
}
// overlays rows for the amount of linebreaks
function postItems(lineCount){
var container = $('<div />');;
for(var i = 1; i <= lineCount; i++) {
container.append('<div class="line">' + i + '</div>');
}
$('.line-wrap').html(container);
}
You'll see at the start of the page, it incorrectly shows 17 lines, and then once you resize it will show the correct amount.
The issue lies in the first line of getLineCount(). Originally you had
var lineWidth = $('.line').width();
but no elements with the class "line" exist yet on your page (since they get added in your postItems() method. I changed it to
var lineWidth = $(".container").width();
instead, and now your code should be working. Snippet posted below:
$(document).ready(function(){
var lineCount = getLineCount();
postItems(lineCount);
$('.answer').text("Ready");
});
$(window).on('resize', function(){
var lineCount = getLineCount();
postItems(lineCount);
$('.answer').text("Number of lines: " + lineCount);
});
// calculates the amount of lines required to hold the items
function getLineCount() {
var lineWidth = $('.container').width();
var itemWidthSum = 0;
var lineCount=1;
$('.item').each(function(index, element) {
if((lineWidth - itemWidthSum) > ($(element).outerWidth())) {
itemWidthSum = itemWidthSum + $(element).outerWidth();
} else {
lineCount++;
itemWidthSum = $(element).outerWidth();
}
});
return lineCount;
}
// overlays rows for the amount of linebreaks
function postItems(lineCount){
var container = $('<div />');;
for(var i = 1; i <= lineCount; i++) {
container.append('<div class="line">' + i + '</div>');
}
$('.line-wrap').html(container);
}
body {
text-align:center;
}
.answer {
position: fixed;
left: 0;
bottom: 0;
}
.container {
position: relative;
width: 50%;
margin: 0 auto;
border: 1px solid #e8e8e8;
display: inline-block;
}
.item {
height: 50px;
padding:0 10px;
background-color: #aef2bd;
float: left;
opacity:0.2;
white-space: nowrap;
}
.line-wrap {
position: absolute;
border: 1px solid red;
width: 100%;
height: 100%;
top:0; left: 0;
}
.line {
height: 50px;
width: 100%;
background-color: blue;
opacity:0.5;
color: white;
transition: all 0.5s ease;
}
.line:hover {
background-color: yellow;
color: #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="item-wrap">
<div class="item">Computer Science</div>
<div class="item">Language</div>
<div class="item">Marketing</div>
<div class="item">Biology</div>
<div class="item">Computer Science</div>
<div class="item">Language</div>
<div class="item">Marketing</div>
<div class="item">Biology</div>
<div class="item">Computer Science</div>
<div class="item">Language</div>
<div class="item">Marketing</div>
<div class="item">Biology</div>
<div class="item">Computer Science</div>
<div class="item">Language</div>
<div class="item">Marketing</div>
<div class="item">Biology</div>
</div>
<div class="line-wrap">
</div>
</div>
<h1 class="answer"></h1>

scroll on overflow if the children count is more than a number

I would like to add scroll on the <ul> element if the number if <li>s is more than a particular number.
Let's say we have 12 children. I would like to show 7 of them and scroll the remain.
This is what I try:
$(document).ready(function(){
$("ul.ul-scrollable, ol.ul-scrollable").each(function (key, val) {
max_num = $(this).attr('data-maxVisible') || 8;
//console.log(max_num);
var lis = $(this).children('li');
if(lis.length > max_num) {
maxHeight = 0;
for(i = 0; i < max_num; i++) {
maxHeight += +$(lis[i]).outerHeight(true);
//console.log(maxHeight);
}
$(this).css({'max-height' : maxHeight + 'px', 'overflow-y' : 'auto'});
}
});
});
ul {
background: white;
width: 70px;
}
ul li {
padding: 3px;
margin: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<ul class="ul-scrollable" data-maxVisible="7">
<li>li1</li>
<li>li2</li>
<li>li3</li>
<li>li4</li>
<li>li5</li>
<li>li6 li6 li6</li>
<li>li7</li>
<li>li8</li>
<li>li9</li>
<li>li10</li>
<li>li11</li>
<li>li12</li>
<li>li13</li>
</ul>
But, the calculation for Height is not applicable correctly.
JS FIDDLE
An easier way of accomplishing the same effect is to grab the 7th index's distance from the top and then setting the max-height to that.
$(document).ready(function(){
$("ul.ul-scrollable, ol.ul-scrollable").each(function (key, val) {
var distance = $(this).children('li').eq(7).offset().top;
$(this).css({'max-height' : distance + 'px', 'overflow-y' : 'auto'});
});
});
ul {
background: white;
width: 70px;
}
ul li {
padding: 3px;
margin: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<ul class="ul-scrollable" data-maxVisible="7">
<li>li1</li>
<li>li2</li>
<li>li3</li>
<li>li4</li>
<li>li5</li>
<li>li6 li6 li6</li>
<li>li7</li>
<li>li8</li>
<li>li9</li>
<li>li10</li>
<li>li11</li>
<li>li12</li>
<li>li13</li>
</ul>

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 can i resolve a conflict in my javascript code?

This is the code:
<script>var jQuery132 = $.noConflict(true);</script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="http://risq.github.io/jquery-advanced-news-ticker/assets/js/jquery.newsTicker.js"></script>
<style>
.newsticker {
max-width: 620px;
margin: auto;
}
.newsticker li {
color: #4e4e4e;
background: #F2F2F2;
overflow: hidden;
height: 28px;
padding: 10px;
line-height: 30px;
list-style: none;
font-size: 20px;
text-align: left;
border-bottom: 1px dotted #2c8162;
}
.newsticker li:hover {
background: #FFF;
}
</style>
<script>
var count = 300;
var counter = setInterval(timer, 1000); //1000 will run it every 1 second
function timer() {
count = count - 1;
if (count == -1) {
clearInterval(counter);
return;
}
var seconds = count % 60;
var minutes = Math.floor(count / 60);
var hours = Math.floor(minutes / 60);
minutes %= 60;
hours %= 60;
document.getElementById("timer").innerHTML = hours + " Hours " + minutes + " Minutes and " + seconds + " Seconds left untill the next news update."; // watch for spelling
}
function news(){
$('body').find('.newsticker').remove();//It will clear old data if its present
var file = "http://newsxpressmedia.com/files/theme/test.txt";
$.get(file, function (txt) {
//var lines = txt.responseText.split("\n");
var lines = txt.split("\n");
$ul = $('<ul class="newsticker" />');
for (var i = 0, len = lines.length; i < len; i++) {
//save(lines[i]); // not sure what this does
$ul.append('<li>' + lines[i] + '</li>'); //here
}
//$ul.appendTo('body').newsTicker({
$ul.appendTo('div.wcustomhtml').newsTicker({
row_height: 48,
max_rows: 2,
speed: 6000,
direction: 'up',
duration: 1000,
autostart: 1,
pauseOnHover: 1
});
});
}
$(function() {
news();
setInterval(function(){
news();
},30000) // it will call every 1 min you can change it
});
</script>
<br><br><span id="timer"></span><br><br>
<script language='JavaScript'>
$(function(){
$("ul#ticker01").liScroll();
});
/*!
* liScroll 1.0
* Examples and documentation at:
* http://www.gcmingati.net/wordpress/wp-content/lab/jquery/newsticker/jq-liscroll/scrollanimate.html
* 2007-2010 Gian Carlo Mingati
* Version: 1.0.2.1 (22-APRIL-2011)
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
* Requires:
* jQuery v1.2.x or later
*
*/
jQuery.fn.liScroll = function(settings) {
settings = jQuery.extend({
travelocity: 0.10
}, settings);
return this.each(function(){
var $strip = jQuery(this);
$strip.addClass("newsticker")
var stripWidth = 1;
$strip.find("li").each(function(i){
stripWidth += jQuery(this, i).outerWidth(true); // thanks to Michael Haszprunar and Fabien Volpi
});
var $mask = $strip.wrap("<div class='mask'></div>");
var $tickercontainer = $strip.parent().wrap("<div class='tickercontainer'></div>");
var containerWidth = $strip.parent().parent().width(); //a.k.a. 'mask' width
$strip.width(stripWidth);
var totalTravel = stripWidth+containerWidth;
var defTiming = totalTravel/settings.travelocity; // thanks to Scott Waye
function scrollnews(spazio, tempo){
$strip.animate({left: '-='+ spazio}, tempo, "linear", function(){$strip.css("left", containerWidth); scrollnews(totalTravel, defTiming);});
}
scrollnews(totalTravel, defTiming);
$strip.hover(function(){
jQuery(this).stop();
},
function(){
var offset = jQuery(this).offset();
var residualSpace = offset.left + stripWidth;
var residualTime = residualSpace/settings.travelocity;
scrollnews(residualSpace, residualTime);
});
});
};
</script>
<style>
/* liScroll styles */
.tickercontainer { /* the outer div with the black border */
border: 1px solid #000;
background: #fff;
width: 500px;
height: 27px;
margin: auto 0;
padding: 0;
overflow: hidden;
}
.tickercontainer .mask { /* that serves as a mask. so you get a sort of padding both left and right */
position: relative;
left: 10px;
top: 8px;
width: 500px;
overflow: hidden;
}
ul.newsticker { /* that's your list */
position: relative;
left: 500px;
font: bold 10px Verdana;
list-style-type: none;
margin: 0;
padding: 0;
}
ul.newsticker li {
float: left; /* important: display inline gives incorrect results when you check for elem's width */
margin: 0;
padding: 0;
background: #fff;
}
ul.newsticker a {
white-space: nowrap;
padding: 0;
color: #ff0000;
font: bold 10px Verdana;
margin: 0 50px 0 0;
}
ul.newsticker span {
margin: 0 10px 0 0;
}
</style>
<ul id="ticker01">
<li><span>10/10/2007</span>The first thing ...</li>
<li><span>10/10/2007</span>End up doing is ...</li>
<li><span>10/10/2007</span>The code that you ...</li>
<!-- eccetera -->
</ul>
I'm using two different jquery newsticker examples:
The first end at:
<br><br><span id="timer"></span><br><br>
From there it's the second one.
I also added now in the top of my code this variable jQuery132:
<script>var jQuery132 = $.noConflict(true);</script>
How and where to use this variable ?
Here is a nice article regarding jQuery conflicts.
Here is code:
<!-- load jQuery version 1.9.0 -->
<script src="jquery-1.9.0.js" type="text/javascript"></script>
<script type="text/javascript">
var $jQuery1_9 = $.noConflict(true);// Here you must need to pass true
//else it will only free $ variable
//and using jQuery with blow libraries
//cause conflict
</script>
//you must load second library later after initializing
//first instance of version and freeup jQuery keyword
//else jQuery keyword will
//cause conflict it you uplaoded both files.
<!-- load jQuery version 1.10.0 -->
<script src="jquery-1.10.0.js" type="text/javascript"></script>
<script type="text/javascript">
var $jQuery1_10 = $.noConflict(true);
</script>
//so now here $ and jQuery both cannot be used
//using $jQuery1_10 will call version 1.10.0 library code
$jQuery1_10( "div p" ).show();
//using $jQuery1_9 will call version 1.9.0 library code
$jQuery1_9( "div p" ).show();

Categories