jquery click function on a d3.js node - php

I want to use jQuery to handle a mouse click on nodes in a force directed network graph. That way, I can run AJAX calls to a PHP page that extracts data about that node via a mySQL query.
But I am struggling how to integrate d3.js with jQuery. I tried this (see jQuery after //click event), but not surprisingly it does not work because 'node' is clearly not the correct ID. When I use HTML div tags, its easy, but with d3.js I am not sure the equivalent ID to use.
Thanks, Tom
<script type="text/javascript">
//click event
$("node").click(function(){
alert("The node was clicked.");
});
//Set margins and sizes
var margin = {
top: 20,
bottom: 50,
right: 30,
left: 50
};
var width = 1920 - margin.left - margin.right;
var height = 1080 - margin.top - margin.bottom;
//Load Color Scale
var c10 = d3.scale.category10();
//Create an SVG element and append it to the DOM
var svgElement = d3.select("body")
.append("svg").attr({"width": width+margin.left+margin.right, "height": height+margin.top+margin.bottom})
.append("g")
.attr("transform","translate("+margin.left+","+margin.top+")");
//Load External Data
d3.json("php/index_network_methy.php", function(dataset){
//Extract data from dataset
var nodes = dataset.nodes,
links = dataset.links;
//Create Force Layout
var force = d3.layout.force()
.size([width, height])
.nodes(nodes)
.links(links)
.gravity(0.1)
.charge(-200)
.linkDistance(100);
//Add links to SVG
var link = svgElement.selectAll(".link")
.data(links)
.enter()
.append("line")
.attr("stroke-width", function(d){ return d.weight/1; })
.attr("class", "link");
//Add nodes to SVG
var node = svgElement.selectAll(".node")
.data(nodes)
.enter()
.append("g")
.attr("class", "node")
.call(force.drag);
//Add labels to each node
var label = node.append("text")
.attr("dx", 24)
.attr("dy", "0.35em")
.attr("font-size", function(d){ return d.influence*1.5>9? d.influence*1.5: 9; })
.text(function(d){ return d.character; });
//Add circles to each node
var circle = node.append("circle")
.attr("r", function(d){ return d.influence/2>15 ? d.influence/2 : 15; })
.attr("fill", function(d){ return c10(d.zone*10); });
//This function will be executed for every tick of force layout
force.on("tick", function(){
//Set X and Y of node
node.attr("r", function(d){ return d.influence; })
.attr("cx", function(d){ return d.x; })
.attr("cy", function(d){ return d.y; });
//Set X, Y of link
link.attr("x1", function(d){ return d.source.x; })
link.attr("y1", function(d){ return d.source.y; })
link.attr("x2", function(d){ return d.target.x; })
link.attr("y2", function(d){ return d.target.y; });
//Shift node a little
node.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
});
//Start the force layout calculation
force.start();
});
</script>

Your listener declaration $("node").click does not reference any element
node is not an element.
You have elements with class node so your jquery declaration should perhaps be
$('.node').click... // (note the dot)
If that doesn't work, it's likely because you're attaching the listener before the elements are in the dom.
A good approach for d3 is to add the a regular javascript listener when you append the node. See d3 handling events

Related

JS-generated GET variables not being read PHP

I am using JavaScript to generate a form's action attribute:
$("#select-font").on('change', function(){
var font = $(this).val();
$("#font-family").val(font);
$(this).css({
'font-family': font
});
$("#edit-doc").css({
'font-family': font
});
// BUG IS HERE --->
$('#save')
.attr('src', '/img/icons2/save.png')
.attr('onclick', '$(this).parents("form").submit();');
$('#save')
.parents('form')
.attr('action',
String($('#save')
.parents('form')
.attr('action')) + '&autosave=true');
});
$("#select-font-size")
.on('change', function(){
var size = $(this).val();
$("#edit-doc").css({
'font-size': size
});
$("#font-size").val(size);
// BUG IS HERE --->
$('#save')
.attr('src', '/img/icons2/save.png')
.attr('onclick',
'$(this).parents("form").submit();');
$('#save')
.parents('form')
.attr('action',
String($('#save')
.parents('form')
.attr('action')) + '&autosave=true');
});
The GET variable is passed to the next page; in the URL bar the location shows up as http://localhost/foo/?var1=a&var2=b&autosave=true. However, when I test the GET variable:
if($_GET["autosave"]){
// some code...
}
The condition is not run. Why can't the PHP see the variable?
Rather than using
if($_GET["autosave"]){
// some code...
}
try:
if (isset($_GET["autosave"])) {
// your code...
}
Also when adding handlers try this, rather than using the inline click handler, use jQuery.on()
$('#save')
.attr('src', '/img/icons2/save.png')
.on('click', function(){
$(this).parents("form").submit();
});

Jquery selector not working after append

I have a php script that I call that returns html in a way that it can be directly inserted into a container or the body and just work (E.X. '<image id="trolleyLogoEdge" class="pictureFrame party" src="tipsyTrixy.png" >'). After appending this text to a div the selector $('#pictureFrame > img:first') won't work. I'm not using event handlers or anything so I don't know why I'm having an issue. My code worked fine when I just had the image tags in the div without any manipulation so I'm assuming it must be a selector issue. I have tested my php output and it is exactly matching the html that was in the div before I decided to dynamically populate the div.
var classType = '';
var classTypePrev = '';
var width = $(window).width();
var height = $(window).height();
var size = (height + width)/2;
var time = 0;
$( document ).ready(function()
{
$.post( "pictureDirectory.php", function( data )
{
$('#picureFrame').append(data);
startSlideshow($('#pictureFrame > img:first'));
});
});
window.onresize = function()
{
width = $(window).width();
};
function startSlideshow(myobj)
{
classType = $(myobj).attr('class').split(' ')[1];
if(classTypePrev != classType)
{
$('.picDescription').animate({'opacity': "0"},{duration: 2000,complete: function() {}});
$('.picDescription.' + classType).animate({'opacity': "1"},{duration: 3000,complete: function() {}});
}
classTypePrev = classType;
myobj.animate({left: "-=" + ((width/2)+ ($(myobj).width()/2) - 150), opacity: '1'},{
duration: 5000,
'easing': 'easeInOutCubic',
complete: function() {}}).delay(2000).animate({left: "-=" + ((width/2)+ ($(myobj).width()/2) + 150), opacity: '0'},{
duration: 5000,
'easing': 'easeInOutCubic',
complete: function()
{
$(myobj).css("left", "100%");
}
});
setTimeout(function()
{
var next = $(myobj).next();
if (!next.length)
{
next = myobj.siblings().first();
}
startSlideshow(next)},9000);
}
Your code that appends the data to the frame has a typo in the ID selector.
$.post( "pictureDirectory.php", function( data )
{
$('#picureFrame').append(data);
^^here
startSlideshow($('#pictureFrame > img:first'));
});
It should probably be
$('#pictureFrame').append(data);
.find() gets the descendants of each element in the current set of matched elements.
> selects all direct child elements specified by "child" of elements specified by "parent".
Try:
startSlideshow($("#pictureFrame").find("img:first"));
If img is not direct child of #pictureFrame, .find() should work.
You should know the difference between
Delegated Event
Direct Event
check this for the difference between direct and delegated events.
If we were to click our newly added item, nothing would happen. This is because of the directly bound event handler that we attached previously. Direct events are only attached to elements at the time the .on() method is called. In this case, since our new anchor did not exist when .on() was called, it does not get the event handler.
check this link to official JQuery Document for further clarification.

Redirecting and then run function on another page?

So I have the code:
header("Location: ".$config['site_url']."index.php#login-box");
Which is my attempt to trigger the html code for a jquery login form if the user is not logged in:
<li><a class="log" href="#login-box"><span class="hover" style="opacity: 0;"></span></a></li>
But when it runs all it does is add #login-box to then end of my url and doesn't trigger the #login-box href. Pretty lame attempt I know, but any ideas?
This is the jquery script, how would I add the code you mentioned to it properly?
$(document).ready(function() {
$('a.login-window2').click(function() {
//Getting the variable's value from a link
var loginBox = $(this).attr('href');
//Fade in the Popup
$(loginBox).fadeIn(300);
//Set the center alignment padding + border see css style
var popMargTop = ($(loginBox).height() + 24) / 2;
var popMargLeft = ($(loginBox).width() + 24) / 2;
$(loginBox).css({
'margin-top' : -popMargTop,
'margin-left' : -popMargLeft
});
// Add the mask to body
$('body').append('<div id="mask"></div>');
$('#mask').fadeIn(300);
return false;
});
// When clicking on the button close or the mask layer the popup closed
$('a.close, #mask').live('click', function() {
$('#mask , .login-popup').fadeOut(300 , function() {
$('#mask').remove();
});
return false;
});
});
</script>
Here is a little snippet that should do the trick, using jQuery as you mentioned:
$(function(){
$("a.login-window2").click(function(){
//Getting the variable's value from a link
var loginBox = $(this).attr("href");
//Fade in the Popup
$(loginBox).fadeIn(300);
//Set the center alignment padding + border see css style
var popMargTop = ($(loginBox).height() + 24) / 2;
var popMargLeft = ($(loginBox).width() + 24) / 2;
$(loginBox).css({
"margin-top" : -popMargTop,
"margin-left" : -popMargLeft
});
// Add the mask to body
$("body").append("<div id=\"mask\"></div>");
$("#mask").fadeIn(300);
return(false);
});
// When clicking on the button close or the mask layer the popup closed
$("a.close, #mask").live("click", function(){
$("#mask , .login-popup").fadeOut(300, function(){
$("#mask").remove();
});
return(false);
});
// Check the hash
var hash = $(location).attr("hash");
if(hash == "#login-box") {
$("a.login-window2").click();
}
});
Put this in your index.php file and run your code from inside the if statement.
It's a mistake in your code.
Use: name="#login-box"
instead of: href="#login-box"

Fetch variable in javascript from a link

I am trying to get a PHP variable to send through javascript and I am having trouble. I am using a jQuery popup I found online and when a user clicks an item, I need that item_id variable to be fetchable in the popup where I want to add a form.
My PHP section.
<a href="#?w=500&item_id='.$stock['id'].'" rel="popup1" class="poplight">
and the Javascript.
$(document).ready(function(){
//When you click on a link with class of poplight and the href starts with a #
$('a.poplight[href^=#]').click(function() {
var popID = $(this).attr('rel'); //Get Popup Name
var popURL = $(this).attr('href'); //Get Popup href to define size
//Pull Query & Variables from href URL
var query= popURL.split('?');
var dim= query[1].split('&');
var popWidth = dim[0].split('=')[1]; //Gets the first query string value
var itemID = dim[0].split('=')[2]; //Gets the second query string value
//Fade in the Popup and add close button
$('#' + popID).fadeIn().css({ 'width': Number( popWidth ) }).prepend('<img src="/layout/close_pop.png" class="btn_close" title="Close Window" alt="Close" />');
//Define margin for center alignment (vertical + horizontal) - we add 80 to the height/width to accomodate for the padding + border width defined in the css
var popMargTop = ($('#' + popID).height() + 80) / 2;
var popMargLeft = ($('#' + popID).width() + 80) / 2;
document.getElementById('popup1').innerHtml = itemID;
//Apply Margin to Popup
$('#' + popID).css({
'margin-top' : -popMargTop,
'margin-left' : -popMargLeft
});
//Fade in Background
$('body').append('<div id="fade"></div>'); //Add the fade layer to bottom of the body tag.
$('#fade').css({'filter' : 'alpha(opacity=80)'}).fadeIn(); //Fade in the fade layer
return false;
});
//Close Popups and Fade Layer
$('a.close, #fade').live('click', function() { //When clicking on the close or fade layer...
$('#fade , .popup_block').fadeOut(function() {
$('#fade, a.close').remove();
}); //fade them both out
return false;
});
});
I added what I thought you work, but it does not var itemID = dim[0].split('=')[2]; //Gets the second query string value and document.getElementById('popup1').innerHtml = itemID;
Use a sophisticated function to retrieve URL query parameters:
function getParameterByName(name, locationObject)
{
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(locationObject.search);
if(results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
[Adopted from here]
Simply call it like so:
getParameterByName('item_id', someLink);
Working Fiddle: http://jsfiddle.net/ADpYT/
You have a simple oversight in your original code ..
When you obtain your dim variable, you get an array with 2 items split at & . In the above code you get ["w=500", "item_id=some_value"] .So in order to get the itemID you have to use dim[1].
var itemID=dim[1].split('=')[1];

How can I append a value from the database to an anchor tag's href attribute?

I am using a popup jquery that pops up a static block of code using a href=#?w=300?h=200 but I need apart from the size to pass a variable from a sql database also a href=?prop_id=$id . I have tried to combine both of them but nothing seems to work does anybody has a clue??
thank you
$(document).ready(function() {
//When you click on a link with class of poplight and the href starts with a #
$('a.poplight[href^=#]').click(function() {
var popID = $(this).attr('rel'); //Get Popup Name
var popURL = $(this).attr('href'); //Get Popup href to define size
//Pull Query & Variables from href URL
var query= popURL.split('?');
var dim= query[1].split('&');
var popWidth = dim[0].split('=')[1]; //Gets the first query string value
//Fade in the Popup and add close button
$('#' + popID).fadeIn().css({ 'width': Number( popWidth ) }).prepend('<img src="to_use/close.png" class="btn_close" title="Close Window" alt="Close" />');
//Define margin for center alignment (vertical horizontal) - we add 80px to the height/width to accomodate for the padding and border width defined in the css
var popMargTop = ($('#' + popID).height() + 80) / 2;
var popMargLeft = ($('#' + popID).width() + 80) / 2;
//Apply Margin to Popup
$('#' + popID).css({
'margin-top' : -popMargTop,
'margin-left' : -popMargLeft
});
//Fade in Background
$('body').append('<div id="fade"></div>'); //Add the fade layer to bottom of the body tag.
$('#fade').css({'filter' : 'alpha(opacity=80)'}).fadeIn(); //Fade in the fade layer - .css({'filter' : 'alpha(opacity=80)'}) is used to fix the IE Bug on fading transparencies
return false;
});
//Close Popups and Fade Layer
$('a.close, #fade').live('click', function() { //When clicking on the close or fade layer...
$('#fade , .popup_block').fadeOut(function() {
$('#fade, a.close').remove(); //fade them both out
});
return false;
});
});
A simpler approach would be to use data- attributes in combination with jQuery's .data() method
HTML
Text
JS
/* in click handler */
var data=$(this).data();
var propId=data.propId;/* same as $(this).data('propId') */
var popWidth=data.w;
/* etc..*/

Categories