Custom function name using unique number - php

I am using a number of HTML5 audio players on one page and I need a means to control them individually. I have so far been using:
<?php $unique = uniqid(); ?>
to generate a unique number. I have them been able to successfully apply this to my player:
<button class="bb-play" onClick="play-<?php echo $unique; ?>()">Play</button>
I am able to apply this within some jQuery, within the function as follows:
function play() { document.getElementById('player-<?php echo $unique; ?>').play(); }
My question is, where my unique number is say 56f295fbe6be3 how can get I get the function play() to appear instead as play-56f295fbe6be3() ?
I appreciate any help you can provide.

Trying to write a function with a unique number in its name is a bad approach. You should rather write a unique function that is able to handle them all.
<script>
function play(that) {
var playerId = that.id;
document.getElementById('player-' + playerId).play();
}
</script>
<button class="bb-play" id="<?php echo $unique; ?>" onClick="play(this)">Play</button>
From a semantic perspective, we're assigning to the <button> element an attribute that says what's the player id and it would make more sense to put it into a data attribute. It comes easier to use jQuery then:
<button class="bb-play" data-player-id="player-<?php echo $unique; ?>">Play</button>
<script>
$("button.bb-play").click(function(){
var playerId = $(this).data('playerId');
$("#" + playerId).play();
});
</script>

HTML:
<button class="bb-play" onClick="play(<?php echo $unique; ?>);">Play</button>
Javascript:
function play(id) { document.getElementById('player-'+id).play(); }

If the buttons and the player are places inside the same parent element, you could work without id's.
<div class="player">
<media .../>
<button class="bb-play">Play</button>
</div>
and the js code
$('.bb-play').on('click', function() {
$('media', $(this).closest('.player')).get(0).play();
});

Why not pass the id number as a variable to the function?
function play_video(id) {
document.getElementById('video-' + id).play();
}
And in the HTML use:
onClick="play_video(<?php echo $unique; ?>)" id="video-<?php echo $unique; ?>"
// onClick="play_video(56f295fbe6be3)" id="56f295fbe6be3"
Then you can just use play_video() for all videos.

Related

get increasing variable from php to jquery

how to pass a variable to jquery with php ?
i have to call the jquery from html this is what is confusing me:
jquery:
$(document).ready(function() {
$('#pre-info').click(function() {
$('#hide').slideToggle("fast");
});
});
now i want a $i after #pre-info and after #hide.
im calling the jqueryScript like this :
thank you.
Okay, here is more code :
<?php
$i =0;
//Make some querys nd stuff
foreach ($all as $one) {
//Here the event 1 is createt but the pre info gets increased with each event listet
echo "<div class='EVENT'><div id='pre-info$i'>";
// get som other tables nd stuff
echo"</div><div id='hide$i' style='display:none;'>";
//now this part is hidden until i click on the pre-info
//hidden Stuff
$i++;
}
?>
<script type="text/javascript">
$(document).ready(function() {
$('.pre-info').click(function() {
var hiddenid=$(this).data('hiddenid');
$('#'+hiddenid).slideToggle();
});
});
</script>
it does still not work, did i miss anything?
for me it looks like pre-info in this javascript needs a reference ( $i) as well ?
maybe i just dont understand the jquery completly..
Ok so you have several hidden divs and for each one you also have a listener to toggle their visibility. The original list comes from php which in turn gets the data from a query.
You could use data attributes to link pre-infos to hidden elements:
$i =0;
foreach ($all as $one) {
echo "<div class='pre-info' data-hiddenid='hide$i'>click me</div>";
echo "<div id='hide$i' style='display:none;'> hidden stuff </div>";
$i++;
}
then you just need one listener on jQuery
jQuery(document).ready(function() {
jQuery('.pre-info').click(function() {
var hiddenid=jQuery(this).data('hiddenid');
jQuery('#'+hiddenid).slideToggle();
});
});
Hope it helps (edit, I wrapped the listener in the document ready event)
By the way, it seems to me you're reinventing the wheel. You could use jQuery UI's accordions or Bootstrap collapsibles with nice, crossbrowser transitions.
If the JS is in .php file, you can just use:
$(document).ready(function() {
$('#pre-info<?php echo $x; ?>').click(function() {
$('#hide<?php echo $x; ?>').slideToggle("fast");
});
});
Your question does not contain enough information to give you more detailed answer, I'm afraid.
you could embed the php variable you require into a hidden html attribute or a data attribute
Hidden Element HTML
<input type="hidden" id="someId" name="someName" value="<?php echo $someVariable?>"/>
Javascript
var someVar = $('#someId').val()
Data HTML
<div id="someId" data-some-var="<?php echo $someVariable?>"></div>
Javascript
var someVar = $("#someId").data("some-var")
Note that if you use data you must include the keyword "data" before whatever you decide to name the attribute

Bind event of a specific element to a specific target

i am using while loop to output data in
<p><?php echo $title;?></p></font></a><button id=show>show()</button> <button id=hide>hide()</button>
my show hide function is
$("#show").click(function () {
$("p").show('fast');
});
$("#hide").click(function () {
$("p").hide('fast');
});
$("#reset").click(function(){
location.reload();
});
now when i am clicking show hide only the first show hide loop is working and it shows/hides all the data not just the one i clicked
Change the code to use this, like so:
$(this).prev('p').show('fast');
You will need to do this in each JQuery .click section.
Edit:
Another good point which has been mentioned, you are using an ID for your element which won't allow this to work on more than one. Your new markup should look like:
<p><?php echo $title;?></p></font></a><button class="show">show()</button>
and the JQuery:
$(".show").click(function () {
$(this).prev('p').show('fast');
});
Welcome to SO. Nice to see that you have formated your first question nicely.
Few things you might want to change.
As you are going through a loop, make sure you use a counter inside the loop and add the counter to the id. This will make the id a unique identifier. Also wrap them inside a div.
$counter = 0;
forloop {
$counter++;
<div>
<p><?php echo $title;?></p></font></a><button id="show<?php echo $counter; ?>">show()</button>
</div>
}
So now your id will be unique.
Now you can write your jquery in the below way.
$("button").click(function () {
$(this).attr('id'); //not required but incase you need the id of the button which was clicked.
$(this).parent().find("p").show('fast');
});
$("button").click(function () {
$(this).parent().find("p").hide('fast');
});
Two things: 1. I think you can only have one element with one id, such as #show. If you want to reference more buttons, you should use a class, such as this: show() (as I understand the buttons are output in a loop, there will be more of them).
Second: inside your javascript code, you do $("p")... - this references all elements on the page. I think you should use $(this) and start from there, check out this article, it explains a lot: http://remysharp.com/2007/04/12/jquerys-this-demystified/
There are many ways to go at this. Here's one:
First, add the loop number to the IDs (let's say it's $i)
<p id="TITLE_<?php echo $i; ?>" style="display:none;"><?php echo $title;?></p>
<input type="button" class="show" data-number="<?php echo $i; ?>"/>
<input type="button" class="hide" data-number="<?php echo $i; ?>" />
Your functions will then be:
$(".show").click(function () {
$("TITLE_" + $(this).data('number')).show('fast');
});
$(".hide").click(function () {
$("TITLE_" + $(this).data('number')).hide('fast');
});
Of course there are ways to do it via JQUERY without the use of the $i.
Edit: To have the tags hidden on page load, either use the style=display:none as I have added in the tag above, or you can use JQuery as follows:
$(document).ready( function() {
$("p[id^=TITLE_]").hide();
// this will retrieve all <p> tags with ID that starts
// with TITLE_ and hide them
});

Passing a parameter to jQuery function?

This looks very simple but I have little experience with jQuery and I can't wrap my head around it.
Let's say I have a dynamically generated HTML table, and in each row of this table is a link:
<a id='edit'>Edit User</a>
Now, the link should call a function with each user's ID as a parameter. I could do that inline liek this:
<a id='edit' onClick='editUser(<?php echo $row['id']; ?>)'>Edit User</a>
But how do I do this in jQuery?
I can call the function like this:
$('a#edit').click(function () {
editUser()
return false;
});
But how do I pass the ID to this function? I know I could first stick it into a hidden field and then get it from there by element id, but surely there's a better way?
I realize all the links would have the same id this way, so should I dynamically create the link ids by appending the user id? But then how do I call the jQuery?
ids must be unique throughout the entire HTML. So you could use a class selector and HTML5 data-* attribute:
<a class="edit" data-id="<?php echo $row['id']; ?>">Edit User</a>
and then:
$('a.edit').click(function () {
var id = $(this).data('id');
// do something with the id
return false;
});
Use data-* attributes to pass parameters.
<a class='edit' data-id='<?php echo $row['id']; ?>'>Edit User</a>
$('a.edit').click(function () {
editUser($(this).data("id"));
return false;
});
As Curt mentionned, the data-id is the way to go, if you're using HTML5. If you're using HTML4, I would pass this in the ID of the link :
<a id='edit-321' class='edit'>Edit User</a>
Then you can do this (and use event.preventDefault() rather than return false !) :
$('a.edit').click(function (evt) {
editUser($(this).attr("id").substring(5));
evt.preventDefault();
});

Javascript: dynamic var names with php?

Probably a dead simple and idiotic question (I'm totally new to javascript):
I have this code that loads a new post by clicking on a "next" or "back"-link. The clicks variable is used to scroll up and down in the sql-limit-statement (using the swapContent function), means you move backward or forward in the database by clicking the links. It works easy and perfectly:
<script type="text/javascript">
var clicks = -1;
function increase()
{
clicks++;
return false;
}
function decrease()
{
clicks--;
return false;
}
</script>
<div id="<?php echo $post['id'].'-multipost'; ?>">
<?php include('views/posts/_postmultipost.php'); ?>
</div>
<div id="<?php echo $post['id']; ?>-next" class="rightbutton" style="display:block;">
next
</div>
<div id="<?php echo $post['id']; ?>-back" class="leftbutton" style="display:none;">
back
</div>
The only problem: As you see I have several posts (post-IDs). But the javascript var "clicks" is always the same. How can I add the post-id into the javascript variable name "clicks", well, something like this :
var <?php echo $post['id']; ?>-clicks = -1;
Of course it doesn't work this way, but I have no clue how to manage it. Any advice? Sorry for this stupid question...
Thanks for your help!
UPDATE
Ok, got the solution: Bryan was right!!!
Changed the code to:
<script type="text/javascript">
var clicks = {};
clicks['<?php echo $post['id']; ?>'] = -1;
function increase()
{
clicks['<?php echo $post['id']; ?>']++;
return false;
}
</script>
The javascript in html stays as it is:
>
Clicks is now an object and will output the following in the swapContent-Function:
count: Array
(
[80] => 0
)
In php you would access the value like this:
foreach($count as $key=>$value) { $count = $value }
In javascript it seems to work a bit different like this:
for(x in clicks)
{
var clicks = clicks[x];
}
Seems to work perfectly now, thanks for your help!!
I'm not incredibly familiar with PHP, so I don't know about php echo. However, would using an object work?
var postClicks = {};
postClicks['<?php echo $post['id']; ?>'] = -1;
As far as I understand you are trying to get this:
var something-clicks = -1;
But in JS something-clicks is an expression - substraction of two variables.
Name tokens in JS cannot contain '-' in contrary with CSS.
You have a syntax error:
onmousedown="increase(); javascript:swapContent('next', clicks, '<?php echo $post['id']; ?>', '<?php echo $post['title']; ?>', '<?php echo $_SESSION['user']['id']; ?>');"
that javascript: is the problem. That property is expected to contain raw JS, and that token is invalid. the javascript used as a protocol is for use on the href property of an a tag.
Other than that, it looks alright. Just type clicks in the JS console of your browser to get the current value returned. Or add console.log('clicks:', clicks); to your function so that the result is logged out on each click.

How to Bind the Onclick event In Jquery in correspondance to Javascript

I Have a select button in php code which Passes the Dynamic generated Row value and How do i do this jquery?
PHP code
<input type ="button" onclick="select(add,'<?php echo $_POST['somevale=ue']?>')"
Javascript
function select (fnname, val){
//Val changes every time
}
How do i acheive the same in Jquery in Putting the click event to the button and passing the Dynamic value and Defining the Function in Jquery?
Use the click handler inside your document ready. Note that add must be a valid function for this to work available in the current scope.
$(function() {
$('input').click(function() {
select(add, 'value you need to pass');
});
function add() {
..
}
});
You can use HTML5 data-attributes here (they don't cause issues in HTML4), like this:
<input type="button" class="add" data-value="<?php echo $_POST['somevalue']?>" />
Then you can fetch it in your function using .attr(), like this:
$(function() {
$(".add").click(function() {
var value = $(this).attr("data-value");
select('add', value); //call original function
//or, put that function's content in here
});
});
Give it a try here

Categories