Can anyone give me a working example of a html page loading it's content with json data using masonry plugin?
I have this code but it doesn't load anything :
PHP file :
<?php
$con = mysqli_connect("localhost", "*", "*", "scratch");
mysqli_query($con,"SET NAMES UTF8"); //é preciso meter isto em utf-8 senão não manda nada
if (!$con)
{
die('Could not connect: ' . mysqli_error());
}
$result = mysqli_query($con,"SELECT * FROM posts ORDER BY IdPost DESC") or die;
while($row = mysqli_fetch_assoc($result))
{
$output[]=$row;
}
print(json_encode($output, JSON_UNESCAPED_UNICODE));
mysqli_close($con);
?>
So, it gets me this json :
[{"IdPost":"5","Title":"Social Networks Blueprints","PostContent":"Main Social Networks Blueprints","TypePublic":"1","IdCategory":"1","PostDate":"2014-11-16 00:00:00","PostImage":"http://static.ddmcdn.com/gif/storymaker-best-hubble-space-telescope-images-20092-514x268.jpg","IdUser":"2"},{"IdPost":"3","Title":"* New iPhone 5 ","PostContent":"Check out this new piece of pure technology","TypePublic":"1","IdCategory":"1","PostDate":"2014-11-16 00:00:00","PostImage":"http://images.visitcanberra.com.au/images/canberra_hero_image.jpg","IdUser":"3"},{"IdPost":"2","Title":" New Samsung Galaxy S4 *","PostContent":"The specs are awesome. Check this graphic","TypePublic":"1","IdCategory":"1","PostDate":"2014-11-16 00:00:00","PostImage":"http://www.studiotv.com.au/wp-content/uploads/2014/07/Klimas-website-edited.jpg","IdUser":"2"}]
now the HTML part of the FILE that matters:
<div id="main">
<div id="main-inner">
<div id="container" class="js-masonry"data-masonry-options='{ "columnWidth": 2, "itemSelector": ".item" }'>
<div class="gride-sizer"></div>
<!--Open Modal faz o pop-up-->
<div class="item open-modal">
<!-- CCODIGO PARA 1 SECÇÃO DE COMMENTS -->
<a href="#">
<img src="images/A.jpg"><img>
</a>
<div class="pinMeta">
<p class="pinDescription">
Tenda suspensa na arvore! O sonho de qualquer campista (ou qualquer bêbado) como eu! Não perca tempo, reserve já a sua!
</p>
<div class="pinSocialMeta">
<a class="socialItem likes" href="#">
1 like
</a>
</div>
</div>
<div class="pinUserAttribution">
<a class="attributionItem firstAttribution " href="#">
<img class="attributionImg" style="" src="images/profile.jpg"></img>
<span class="attributionTitle">
Publicado por
</span>
<span class="attributionName">
Pihh
</span>
</a>
<a class="attributionItem lastAttribution " href="#">
<img class="attributionImg" style="" src="images/profile.jpg"></img>
<span class="attributionTitle">
em
</span>
<span class="attributionName">Categoria 1</span>
</a>
</div>
</div>
It might miss a div or two because I copy-pasted it but when using the masonry plugin without json ( for fixed values it loads perfectly ).
now the CSS file:
#container .grid-sizer { width:100%;}
#container .item { width:15%; margin: 14px 7px 0px; background-color:#fff; border-radius: 4px 4px 4px 4px; box-shadow: 0px 4px 5px #888888; }
#container .item img { width:100%; height:400%%; border-radius: 4px 4px 0px 0px; }
#container .item img:hover { background:none repeat scroll rgba(255,255,255,0.1) }
#container .item w2 { width:200%; }
/*placed .open-modal at 400px so I can garantee that page remains in same position on when modals opened*/
.open-modal{
position: relative;
top: 400px;
}
So, this is it, I'm having quite a trouble to make this working and I'm totaly blank on this ( probably because I'm new to html and CSS, my expertise is on android - even the asynk tasks of android are really more easy for me and probably I'm having problems in that but if some one could give me a piece of working code I'll be trully greatfull and start to try to understand it .
Best regards,
Pihh
EDIT: I totally forgot the js part !
<script>
var body = $('body');
toggleModal = function () {
body.toggleClass('body-locked');
modal_container.toggleClass('dp-block');
$.ajax({
type: "POST",
url: "http://localhost/website2/posts.php",
data: '{ "pIdPost":' + $(this).attr('data-item') + ' }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var Posts = response;
// var Posts = response.d;
var $boxes;
$.each(Posts, function (index, post) {
$boxes = $('<img src="' + post.PostImage + '" />');
$('#modal-main').html($boxes); //
// $('.modal-userthumb').attr('src', post.Users.UserImage);
// $('.modal-descriptioncreator').text(post.Users.Name + ' ' + post.Users.Surname);
$('.modal-descriptiontimeago').text('• 4 days ago');
$('.modal-descriptioncontent').text(post.PostContent);
});
$('#container').append($boxes);
$('#container').masonry('appended', $boxes, true);
$('#container').masonry();
},
failure: function (msg) {
alert(msg);
}
});
}
</script>
Related
having an issue with the jquery sortable code - it's not so much the jquery but how my list of images is showing. Prior to adding the sortable code it displayed the images in my wrapper in a grid like formation perfectly - now I have added a little style from the jquery it seems to have thrown it but im not sure why...
here is the Jquery style:
<style>
#sortable { list-style-type: none; margin: 0; padding: 0; width: 450px; }
#sortable li {float: left; }
</style>
Here is my list of images that worked perfectly ok before:
<div id="images">
<hr style="margin-top: 10px" />
<ul id="sortable">
<?php
// get folio for user
if(isset($_GET['userid'])) {
$query = 'SELECT * FROM folio WHERE userid=\'' . $_GET['userid'] . '\' ORDER BY ord';
}
else {
$query = 'SELECT * FROM folio WHERE userid=\'' . $_SESSION['userid'] . '\' ORDER BY ord';
}
$result = mysqli_query($connection, $query);
if(!$result) {
// error with MYSQL
die('Failed to retrieve images! - ' . mysqli_error($connection));
}
// list images
$numRows = mysqli_num_rows($result);
if($numRows < 1) {
echo '';
}
else {
$filepath = 'uploads/folio/';
while($imagerow = mysqli_fetch_assoc($result)) {
?>
<li>
<div class="outimgbox"> <a class="fancybox fancybox.ajax" rel="gallery1" style="text-decoration: none;" data-fancybox-type="ajax" href="profile_image_fancybox.php?imgid=<?php echo $imagerow['imgid']; ?>">
<div id="mainwrapper">
<div id="box-3" class="box"> <img class="uploads" src="<?php echo $filepath . $imagerow['filename']; ?>" alt="<?php echo $imagerow['description']; ?>"/> <span class="caption fade-caption">
<h3 ><?php echo $imagerow['title']; ?></h3>
</span> </div>
</div>
</a> </div>
</li>
<!-- class outingbox -->
<?php }} ?>
</ul>
For some odd reason:
<style>
#sortable { list-style-type: none; }
#sortable li {float: left; }
</style>
This resolved the issue....
There is a list of checkboxes. User clicks on image of a "unchecked checkbox". Ajax sends request to php script which updates database and echo's new image source of a "checked checkbox". This works fine, and is below:
HTML:
<img src="<?php echo ( $box->complete == 1 ) ? "/images/checkbox-filled.png" : "/images/checkbox-empty.png" ?>" id="checkbox-<?php echo $box->id ?>" />
markBox.js:
$.ajax( {
type: "POST",
url: "/scripts/markBox.php",
data: data,
cache: false,
success: function( imageSource ) {
image.attr( 'src', imageSource );
}
} );
markBox.php:
//Return result
if ( $box->complete == 1 )
echo "/images/checkbox-filled.png";
else
echo "/images/checkbox-empty.png";
exit;
The challenge is that I have php function that is called earlier, above the list of checkboxes, to display to user how boxes are checked and how many are not. I want this box to be called and refresh as the image does. How do I rerun the php function to run again once the ajax comes back?
HTML:
<div class="markBox"><?php echo $results->getCountComplete() ?> Complete</div>
<div class="markBox"><?php echo $results->getCountNotComplete() ?> Incomplete</div>
you don't need ajax at all: (unless you don't want to store your data to a database or a file): I hope this helps:
http://jsfiddle.net/teeEx/
HTML:
<span class="checked"> </span>
<span class="unchecked"> </span>
<span class="unchecked"> </span>
<div id="result"></div>
CSS:
a{
text-decoration: none;
}
span{
display: block;
width: 30px;
height: 30px;
margin: 20px;
}
span.checked{
background: green;
}
span.unchecked{
background: black;
}
JS:
$('a').click(function(){
var a_obj = $(this);
var obj = a_obj.children('span');
if( obj.is('.checked')){
obj.removeClass('checked').addClass('unchecked');
} else {
obj.removeClass('unchecked').addClass('checked');
}
var all = a_obj.parent();
var countChecked = all.find('span.checked').length;
var countunChecked = all.find('span.unchecked').length;
$('#result').html('checked '+countChecked+'; unckecked: '+countunChecked);
});
I am creating a chat for my site. It works fine, but a function isn't working inside of a HTML button. I have 3 files I use for it, and one line isn't working.
Before, I had an issue where I set the Javascript function, create the button, and it would say the function doesn't exist. I fixed that, by putting the function below the buttons.
Each button shows an online member, who is on your friends list.
The error I get in confusing me, as I have no idea how this is being caused.
Error: 'Uncaught SyntaxError: Unexpected token } users.php:3'
(users.php is the page I was on, if I change it that changes to the page name.)
With chrome, I can click on the error, that brings up this: 'window.script1357688207590=1;'
Scripts (sorry for being so long):
Script 1: (main script):
var username = '[error]';
$.ajax({
url: 'bchat.php',
type: 'post',
data: { method: 'method2' },
success: function(data){
username = data;
}
});
$.ajax({
url: 'bchat.php',
type: 'post',
data: { method: 'method1' },
success: function(data){
if(data!='do not show chat'){
function ToggleChat(tof){
if(tof == true){
$('#chatWindow').css('visibility','visible');
}else{
$('#chatWindow').css('visibility','hidden');
}
}
$('body').append('\
<div id=chatWindow style="background:white; visibility
:hidden; position: fixed; bottom: 0; right: 0; margin-top:-30px; width:200px; height:350px;">\
<div style="width:100%; height:100%; border:solid black 1px;">\
<div style="hieght:20px; background:rgb(40,40,40); color:white;">\
'+data+'<span> </span>'+username+'\
<button id=chat_close style="float:right; background:rgba(0,0,0,0); border:none; color:white;">\
Close\
</button>\
</div>\
<div id=chatOnline style="overflow:auto;">\
</div>\
</div>\
</div>\
<div id=chat__window style="background:white; visibility:hidden; position: fixed; bottom: 0; right: 200; margin-top:-30px; margin-left:-400px; width:200px; height:350px;">\
\
</div>\
<div id=chat style="position: fixed; bottom: 0; right: 0;">\
<button id=chat_open style="border:none; padding:5px; color:whiteSmoke; background-image: -ms-linear-gradient(bottom, #4A4A4A 0%, #00070A 100%);background-image: -moz-linear-gradient(bottom, #4A4A4A 0%, #00070A 100%);background-image: -o-linear-gradient(bottom, #4A4A4A 0%, #00070A 100%);background-image: -webkit-gradient(linear, left bottom, left top, color-stop(0, #4A4A4A), color-stop(1, #00070A));background-image: -webkit-linear-gradient(bottom, #4A4A4A 0%, #00070A 100%);background-image: linear-gradient(to top, #4A4A4A 0%, #00070A 100%); width:200px; height:30px;">\
'+data+' <span> </span>Chat\
</button>\
</div>');
$('#chat_open').click(function() {
ToggleChat(true);
});
$('#chat_close').click(function() {
ToggleChat(false);
});
}
}
});
//
//update online users
//
function updateOnline(){
$.ajax({
url: 'bchat.php',
type: 'post',
data: { method: 'method3' },
success: function(data){
$('#chatOnline').html(data);
}
});
}
updateOnline();
setInterval(updateOnline,5000);
Script 2 (function script):
function chatWith(url,un){
$('#chat__window').html('<div style="width:100%; height:100%; margin-top:-30px; border:solid black 1px;"><div style="hieght:20px; background:rgb(40,40,40); color:white;">'+url+'<span> </span>'+un+'<button id=chat_chatting_close style="float:right; background:rgba(0,0,0,0); border:none; color:white;">Close</button></div><div id=chat_chats style="overflow:auto;"></div></div>');
$('#chat__window').css('visibility','visible');
}
PHP script (bchat.php):
<?php
include_once("./login_manager_php_file.php");
if($username&&$userid){
$method = $_POST['method'];
if($method){
if($method=='method1'){
$url = $images['logged_in'];
$html = "<img src='".$url."' width=7.5 height=7.5/>";
}elseif($method=='method2'){
echo $username;
}elseif($method=='method3'){
$friends_q = mysql_query("SELECT * FROM friends WHERE `with`='$username' OR `friender`='$username'");
$thtml = '';
if($friends_q){
while($friend = mysql_fetch_assoc($friends_q)){
if($friend['with']==$username){
$usern = $friend['friender'];
}else{
$usern = $friend['with'];
}
$url = '';
if(ifLoggedIn($usern)===true){
$url = $images['logged_in'];
}else{
$url = $images['logged_out'];
}
if(ifLoggedIn($usern)===true && $usern != $username){
$on = $url;
$html = "
<button onClick='
chatWith('$url','$usern');
'
style='border:none; background:rgba(0,0,0,0);'><img src='".$url."' width=7.5 height=7.5/>";
$thtml = $thtml.$html.$usern.'</button><br/>';
}
}
}
echo $thtml;
}elseif($method==='method4'){
if($_POST['usrn']){
$url = '';
if(ifLoggedIn($_POST['usrn'])===true){
$url = $images['logged_in'];
}else{
$url = $images['logged_out'];
}
echo "<img src='".$url."' width=7.5 height=7.5/>";
}else{
echo '[error]';
}
}
}
}else{
echo 'do not show chat';
}
?>
Try to change the php to add an id attribute to the button, or class if there is going to be more than one. Also, remove the onclick attribute
<button class="btnChat" ...
Just realized you will need to add in the parameters as well. I would add those to data attributes on the button.
<button class="btnChat" data-url="$url" data-usern="$usern"
You will need to make sure the $url and $usern are escaped properly
then in the script 2 file you can hook up the click event for that button:
$(function(){
$('body').on('click','.btnChat',function(){
chatWith($(this).data('url'),$(this).data('usern'));
});
});
I am trying to include a Facebook like button iFrame that has PHP in it:
<iframe src="http://www.facebook.com/plugins/like.php?href=<?php echo $row['id']; ?>&send=false&layout=button_count" style="border: medium none; overflow: hidden; width: 115px; height: 21px;" allowtransparency="true" frameborder="0" scrolling="no"></iframe>
when the site loads this, it displays as in a list:
<ul class="recent-list">
<?php
require("inc/connect.php");
$result = mysql_query("SELECT * FROM entries ORDER BY id DESC LIMIT 0, 20", $link);
while($row = mysql_fetch_array($result)){ ?>
<li id="qoute-<?php echo $row['id']; ?>" class="quote-wrap group">
<span>
<iframe src="http://www.facebook.com/plugins/like.php?href=<?php echo $row['id']; ?>&send=false&layout=button_count" style="border: medium none; overflow: hidden; width: 115px; height: 21px;" allowtransparency="true" frameborder="0" scrolling="no"></iframe>
</span>
<div class="quote">
<p>
<?php echo htmlentities($row['quote']); ?>
</p>
</div><!-- /.quote -->
</li>
<?php } ?>
</ul>
But when someone click a button that fetches more list-items, the iFrame should be included...
function getQuotes(start, limit) {
//Clear the recent list element
//$(".recent-list").html("");
var recent = $(".recent-list");
$(".recent-list li").animate({opacity: 0.1} , 800).hide(500);
$.ajax({
url: "quotes.php?start=" + start + "&limit=" + limit,
success: function (data) {
data = jQuery.parseJSON(data)
console.log("success");
//Data should now be a javascript array of objects.
for (i = 0; i < data.length; i++) {
var newElem = jQuery("<li></li>").attr('id', data[i].id).addClass('quote-wrap-group');
newElem.append("<div class='quote'><p>" + data[i].quote + "</p></div>");
$(".recent-list").append(newElem);
}
}
});
}
var currentIndex = 0;
$("#more").click(function () {
getQuotes(currentIndex, 20);
currentIndex += 10;
});
When I try to include the iframe in the js above, nothing happens. No error, nothing is returned...
quotes.php:
$start = $_GET['start'];
$limit = $_GET['limit'];
$sql = "SELECT * FROM entries ORDER BY id DESC LIMIT ".$start.", ".$limit;
$result = mysql_query($sql, $link) or die("Error in query: ".mysql_error());
$data = array();
while($row = mysql_fetch_array($result)) {
array_push($data, $row);
}
echo(json_encode($data));
live version. Click "Get more". The quotes appear, but no like button.
http://kdevs.site40.net/#more
you didn't add the iframe tags while building the <li> it the success function
all you did was adding (for each row):
<li id="54" class="quote-wrap-group">
<div class="quote">
<p>fdggfdgdgdgfdg</p>
</div>
</li>
a better approach will be to make the whole list items on server side, and echo it, and then append the html that you received in the success to the existing list
for example:
your php will look like this:
$data = getData();//Get the data from the database here;
foreach($data as $row):
?>
<li id="qoute-<?php echo $row["id"];?>" class="quote-wrap group">
<span>
<iframe src="http://www.facebook.com/plugins/like.php?href=<?php echo row["id"];?>&send=false&layout=button_count" style="border: medium none; overflow: hidden; width: 115px; height: 21px;" allowtransparency="true" frameborder="0" scrolling="no"></iframe>
</span>
<div class="quote"><p><?php echo $row["quote"];?></p></div>
</li>
<?php endforeach; ?>
your javascript function will be:
function getQuotes(start, limit){
$.ajax({
url:"quotes.php?start=" + start + "&limit=" + limit,
dataType: "html",
success: function(response){
$("ul.recent-list").append(response);
}
});
}
this of course trying to show the principle, and not necessarily be the exact code you need to write. You need to add the other functionality (like hiding the previous quotes etc...)
I did some googling and figured I'm probably experiencing so called "event bubbling" that I've never heard of but are not surprised by it's existance. I want it to fire only once and I'm wondering how to fix this.
Basically, I have this small code snippet:
$('.bggallery_images').click(function () {
alert('test');
});
This is supposed to fire once from a php snippet that basically adds an image of each image from a specific folder. It then outputs an echo string where each image has the class of "bggallery_images".
PHP snippet looks like this:
<?php
$dirname = "img";
$images = scandir($dirname);
$ignore = Array(".", "..");
foreach($images as $file)
{
if(!in_array($file, $ignore))
{
echo "<img class=\"bggallery_images\" src=\"$dirname/$file\" />";
};
}
?>
This all generates the html markup that looks like this for each image:
<img src="img/WhitePattern6.gif" class="bggallery_images">
What is happening here?
Here's the rendered output from FireBug:
<div id="gallery_lightbox" style="height: 215px; z-index: 4; display: block;">
<div id="close"></div>
<h2><cufon class="cufon cufon-canvas" alt="Velg " style="width: 39px; height: 20px;"><canvas width="49" height="23" style="width: 49px; height: 23px; top: -4px; left: 0px;"></canvas><cufontext>Velg </cufontext></cufon><cufon class="cufon cufon-canvas" alt="bakgrunnsbilde" style="width: 123px; height: 20px;"><canvas width="129" height="23" style="width: 129px; height: 23px; top: -4px; left: 0px;"></canvas><cufontext>bakgrunnsbilde</cufontext></cufon></h2>
<div class="bggallery_images">testererererer</div>
<img src="img/Bakgrunner/4462-v4.jpg" class="bggallery_images"><img src="img/Bakgrunner/5922.gif" class="bggallery_images"><img src="img/Bakgrunner/BluePattern.gif" class="bggallery_images"><img src="img/Bakgrunner/Brown1.gif" class="bggallery_images"><img src="img/Bakgrunner/Brown2Pattern.jpg" class="bggallery_images"><img src="img/Bakgrunner/BrownPattern.jpg" class="bggallery_images"><img src="img/Bakgrunner/Brownn.gif" class="bggallery_images"><img src="img/Bakgrunner/GrayPattern.gif" class="bggallery_images"><img src="img/Bakgrunner/GreenPattern3.gif" class="bggallery_images"><img src="img/Bakgrunner/OrangePattern.gif" class="bggallery_images"><img src="img/Bakgrunner/PurplePattern.gif" class="bggallery_images"><img src="img/Bakgrunner/PurplePattern2.gif" class="bggallery_images"><img src="img/Bakgrunner/RedPattern3.gif" class="bggallery_images"><img src="img/Bakgrunner/RedPattern4.gif" class="bggallery_images"><img src="img/Bakgrunner/RedPattern5.gif" class="bggallery_images"><img src="img/Bakgrunner/Tiled_Wallpaper__Green_Texture_by_knitetgantt.png" class="bggallery_images"><img src="img/Bakgrunner/WhitePattern4.gif" class="bggallery_images"><img src="img/Bakgrunner/WhitePattern5.gif" class="bggallery_images"><img src="img/Bakgrunner/WhitePattern6.gif" class="bggallery_images"><img src="img/Bakgrunner/WhitePattern7.gif" class="bggallery_images"><img src="img/Bakgrunner/WhitePurple.jpg" class="bggallery_images"><img src="img/Bakgrunner/YellowPattern.gif" class="bggallery_images"><img src="img/Bakgrunner/vintage-wallpaper.jpg" class="bggallery_images">
</div>
Edit: Here's the js.js file basically. I didn't include the kwicks slidemenu script though.
/* ********************************************** */
/* DOCUMENT READY */
/* ********************************************** */
$(document).ready(function () {
bg_gallery();
});
/* ********************************************** */
/* Background gallery changer */
/* ********************************************** */
function bg_gallery() {
// Sett nytt bakgrunnsbilde i CSSen
var originalBG = $('#wrapper').css('background-image');
$('.bggallery_images').click(function () {
var newBG = "url('" + $(this).attr('src');
var fullpath = $(this).attr('src');
var filename = fullpath.replace('img/Bakgrunner/', '');
$('#wrapper').css('background-image', newBG);
alert('test');
// Lagre til SQL
/*alert('Test');
$.ajax({
url: 'save_to_db.php', // The url to your function to handle saving to the db
data: filename,
dataType:'Text',
type: 'POST', // Could also use GET if you prefer
success: function(data) {
// Just for testing purposes.
//alert('Background changed to: ' + data);
}
});*/
});
// Få frem galleriet
$('.bggallery_current_image').click(function () {
$('html, body').animate({scrollTop:0}, 'slow');
$('#gallery_lightbox').css('height','215px'); // Sett høyde på lightbox-dings
$('#gallery_lightbox').css('z-index','4'); // Sørg for at boksen er i øverste lag
$('body').append('<div id="bggallery_overlay"></div>');
$('#bggallery_overlay').css('height', $(document).height ());
$('#bggallery_overlay').css('width', $(document).width ());
$('#bggallery_overlay').fadeIn('fast',function(){$('#gallery_lightbox').fadeIn('slow');});
});
$('#close').click(function () {
$('#bggallery_overlay').fadeOut('fast',function(){$("#bggallery_overlay").remove();}); //callback, vent
$('#gallery_lightbox').fadeOut('slow');
});
};
/* ********************************************** */
/* Content loader (swoosh ut-swosh inn) */
/* ********************************************** */
/* Load kun fra dynload-klasser, må wrappe en div f. eks rundt slike a href linker */
$('.dynload').die('click').live('click', function () {
$('#ajaxloader').fadeIn('fast');
$('#ajaxloaderfridge').fadeIn('fast');
var href = this.href + ' #content';
var height_initially = $('#container').height();
$('#content').slideUp('fast', function () {
$('#content').fadeOut('fast');
var height_current = $('#container').height();
$(this).load(href, '', function (data) {
createSlidemenus();
bg_gallery();
$('#ajaxloader').fadeOut('fast');
$('#ajaxloaderfridge').fadeOut('fast');
$("#content").animate({
height: 'show',
opacity: 'show'
}, 'normal');
$('#content').show('fast');
Cufon.replace('h1, h2, h3, h4, .menuwrapper', {
fontFamily: 'advent'
});
});
});
return false;
});
$(createSlidemenus);
function createSlidemenus() {
$('#kontrollpanel .slidepanels').kwicks({
min: 42,
spacing: 3,
isVertical: true,
sticky: true,
event: 'click'
});
}
Check out the following link to clarify event bubbling: http://www.quirksmode.org/js/events_order.html
You can prevent bubbling by just returning "false" from the event handler:
$('.bggallery_images').click(function () {
alert('test');
return false;
});
Edit: This code works without producing two alerts so it must be something external to this.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/DTD/strict.dtd">
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
</head>
<body>
<div id="gallery_lightbox" style="height: 215px; z-index: 4; display: block;">
<div id="close"></div>
<h2>
<cufon class="cufon cufon-canvas" alt="Velg " style="width: 39px; height: 20px;">
<canvas width="49" height="23" style="width: 49px; height: 23px; top: -4px; left: 0px;"></canvas>
<cufontext>Velg</cufontext>
</cufon>
<cufon class="cufon cufon-canvas" alt="bakgrunnsbilde" style="width: 123px; height: 20px;">
<canvas width="129" height="23" style="width: 129px; height: 23px; top: -4px; left: 0px;"></canvas>
<cufontext>bakgrunnsbilde</cufontext>
</cufon>
</h2>
<div class="bggallery_images">testererererer</div>
<img src="http://google.com/images/srpr/nav_logo13.png" class="bggallery_images"/>
<img src="http://google.com/images/srpr/nav_logo13.png" class="bggallery_images"/>
</div>
<script type="text/javascript">
$('.bggallery_images').click(function () {
alert('test');
});
</script>
</body>
</html>
I've created a test page from the html and js instruction you posted and can't reproduce your error- the alert only fires once. I'm using this for a jquery reference:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"></script>
and this at the end to start things up
<script>
$('.bggallery_images').click(function() {
alert('test');
});
</script>
you're doing something you're not telling us about or firebug is lying to you. it's possible the html that firebug is showing you (as it's interpreted) is different than the physical source of the page. can you post a complete example of your output which demonstrates the problem?
You might want to have a look at the jquery .bind() method.
The following is taken from the jquery docs page
Example: Cancel a default action and prevent it from bubbling up by returning false:
$("form").bind("submit", function() { return false; })
Example: Stop an event from bubbling without preventing the default action by
using the .stopPropagation() method.
$("form").bind("submit", function(event) {
event.stopPropagation();
});