Solved

how to attribute a value to a javascript variable from within the page

Posted on 2014-10-02
4
349 Views
Last Modified: 2014-10-03
I need to receive the value of an input and attribute it into a javascript variable. I need the variable "circles" to be dynamically attributed from an input within the same page without reloading the page. The code below writes the circles so it should also be able to cope with the changes from the input variable being changed within the page...

      <script type="text/javascript">
		var circles= 5
		for (i=0; i < numberOfNodes; i++)
		{
			document.write("<div class='circle animate orange'></div>")
		}
		document.write("<div id='circle' class='circle'></div>")
	</script>  

Open in new window



Any help would be much appreciated.
Cheers
0
Comment
Question by:R Wolf
  • 2
4 Comments
 
LVL 58

Expert Comment

by:Gary
Comment Utility
You mean something like this

var circles= $("#someinput").val()
0
 
LVL 51

Expert Comment

by:Julian Hansen
Comment Utility
I think Gary has covered it with JQuery - you seem to be using straight JS but have posted to the JQuery group so just  need to understand more.

I am assuming this follows on from your previous question on animating circles based on an AJAX request. Is the value you are wanting to use the return of the AJAX call or something the user inputs?

If the latter you have not shown us where the variable is being input. Your loop is also confusing because it uses numberOfNodes as the loop terminator and the variable circles is not used - should they be the same thing.

Give us a bit more of the code and context specifically can you be a bit more clear on what you mean by
"The code below writes the circles so it should also be able to cope with the changes from the input variable being changed within the page."
0
 

Author Comment

by:R Wolf
Comment Utility
Yep julianH you are completely right, I used an older piece of code sorry. Yes I need to retrieve with Ajax the number of circles, it must be the number of records from a SQL query, but even though you guys said it was an easy concept I couldn't make it work...
Here is the code:


<html><head>
<meta http-equiv="content-type" content="text/html; charset=windows-1252">
<title>test</title>
<style type="text/css">
#circle-container {
  position: relative;
  width: 500px;
  height: 500px;
  margin: 0 auto;
  border: 0px solid green;
}
.circle {
  position: absolute;
  width: 40px;
  height: 40px;
  border-radius: 40px;
  background: red;
  left: 230px;
  top: 230px;
}
.blue {
  background: blue;
}
.green {
  background: green;
}
.yellow {
  background: yellow;
}
.orange {
  background: orange;
}
.pink {
  background: pink;
}
</style>
</head>
<body>

<div id="circle-container">
	<script type="text/javascript">
		var numberOfNodes = 9
		for (i=0; i < numberOfNodes; i++)
		{
			document.write("<div class='circle animate orange'></div>")
		}
		document.write("<div id='circle' class='circle'></div>")
	</script>  
</div>
<script src="jquery.js"></script>
<script type="text/javascript">
var clicked = false;
var distanceToMove = 100;
$(function() {
  $('#circle').click(function() {
    if (clicked) return;
    clicked = true;
    var total_circles = $('#circle-container .circle.animate').length;
    var angle = (Math.PI * 2 / total_circles)
    $('#circle-container .circle.animate').each(function(indx, item) {
      var top = distanceToMove * Math.cos(angle*(indx-1));
      var left = distanceToMove * Math.sin(angle *(indx-1)); 

      $(this).animate({left: "+=" + left, top: "+=" + top}, 1000);
    });
  });
});
</script>
<script src="Test_files/plugin.js" type="text/javascript"></script></body></html>

Open in new window


Thanks.
0
 
LVL 51

Accepted Solution

by:
Julian Hansen earned 500 total points
Comment Utility
There a couple of ways of doing this depending on how you want to handle it. The easiest is to just execute a .load() function on the #circle-container div and have the called script return the actual HTML for the circles. If you want to create the div's in the page after the call then the code below should get you going in the right direction
First here is my preferred way
...
   // Load content dynamically using the JQuery .load function
   $('#circle-container').load('getCircles.php');
...
   // Refer code below on how to update centre circle click event for dynamic binding.

Open in new window

getCircles.php
...
// DB Code to get number of cirlces
for($i =1; $i < $numCircles;$i++) {
   echo '<div class="circle animate orange"></div>';
}
echo  '<div id="circle" class="circle animate orange"></div>';

Open in new window

AJAX Code for building div's in script
<html><head>
<meta http-equiv="content-type" content="text/html; charset=windows-1252">
<title>test</title>
<style type="text/css">
#circle-container {
  position: relative;
  width: 500px;
  height: 500px;
  margin: 0 auto;
  border: 0px solid green;
}
.circle {
  position: absolute;
  width: 40px;
  height: 40px;
  border-radius: 40px;
  background: red;
  left: 230px;
  top: 230px;
}
.blue {
  background: blue;
}
.green {
  background: green;
}
.yellow {
  background: yellow;
}
.orange {
  background: orange;
}
.pink {
  background: pink;
}
</style>
</head>
<body>

<div id="circle-container">
</div>
<script src="jquery.js"></script>
<script type="text/javascript">
var clicked = false;
var distanceToMove = 100;
$(function() {
  // AJAX Call on Page Load - however you
  // can link to an in page event as well
  // This code works on the premise that
  // the AJAX call just returns number of 
  // circles and it builds the HTML.
  // You could also have the HTML constructed
  // in the AJAX script and return it as a block
  // of text - that would be my preferred solution
  // which would look something like
  // $('#circle-container').load('getCircles.php');
  // getCicles.php will return the html and the
  // .load will add it to the container.
  $.ajax({
  url : 'getCircles.php',
  success: function(response) {
    // It was not clear if number of circles
    // includes the centre or not. Code below
    // assumes it does so it starts from 1. If
    // not then change start of loop to 0
    for(i = 1;i < response;i++) {
      $('#circle-container').append(
        // Modify as needed to add specific classes - you could for instance
        // have classes as circle1, circle2 etc and then use the loop variable
        // to construct the class name.
        $('<div/>').addClass('circle').addClass('animate').addClass('orange');
      )
      $('#circle-container').append(
        $('<div/>').attr('id','circle'), addClass('circle').addClass('animate').addClass('orange');
      )
    }
  }
  });
  // Change this so that click event is dynamically bound to the controlling circle.
  $('#circle-container').on('click', '#circle', (function() {
    if (clicked) return;
    clicked = true;
    var total_circles = $('#circle-container .circle.animate').length;
    var angle = (Math.PI * 2 / total_circles)
    $('#circle-container .circle.animate').each(function(indx, item) {
      var top = distanceToMove * Math.cos(angle*(indx-1));
      var left = distanceToMove * Math.sin(angle *(indx-1)); 

      $(this).animate({left: "+=" + left, top: "+=" + top}, 1000);
    });
  });
});
</script>
<script src="Test_files/plugin.js" type="text/javascript"></script></body></html>

Open in new window

0

Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now