I would like to use the following script to display dynamic breaking news on the home page of my site, this dynamic code is run via mysql
<script language="JavaScript1.2">
//Specify the marquee's width (in pixels)
var marqueewidth="780px"
//Specify the marquee's height
var marqueeheight="50px"
//Specify the marquee's marquee speed (larger is faster 1-10)
var marqueespeed=2
//configure background color:
var marqueebgcolor=""
//Pause marquee onMousever (0=no. 1=yes)?
var pauseit=1
//Specify the marquee's content (don't delete <nobr> tag)
//Keep all content on ONE line, and backslash any single quotations (ie: that\'s great):
var marqueecontent='<nobr><font face="Arial"><h3>Example Scrolling Breaking News</h3></font></nobr>'
////NO NEED TO EDIT BELOW THIS LINE////////////
marqueespeed=(document.all)? marqueespeed : Math.max(1, marqueespeed-1) //slow speed down by 1 for NS
var copyspeed=marqueespeed
var pausespeed=(pauseit==0)? copyspeed: 0
var iedom=document.all||document.getElementById
if (iedom)
document.write('<span id="temp" style="visibility:hidden;position:absolute;top:-100px;left:-9000px">'+marqueecontent+'</span>')
var actualwidth=''
var cross_marquee, ns_marquee
function populate(){
if (iedom){
cross_marquee=document.getElementById? document.getElementById("iemarquee") : document.all.iemarquee
cross_marquee.style.left=parseInt(marqueewidth)+8+"px"
cross_marquee.innerHTML=marqueecontent
actualwidth=document.all? temp.offsetWidth : document.getElementById("temp").offsetWidth
}
else if (document.layers){
ns_marquee=document.ns_marquee.document.ns_marquee2
ns_marquee.left=parseInt(marqueewidth)+8
ns_marquee.document.write(marqueecontent)
ns_marquee.document.close()
actualwidth=ns_marquee.document.width
}
lefttime=setInterval("scrollmarquee()",20)
}
window.onload=populate
function scrollmarquee(){
if (iedom){
if (parseInt(cross_marquee.style.left)>(actualwidth*(-1)+8))
cross_marquee.style.left=parseInt(cross_marquee.style.left)-copyspeed+"px"
else
cross_marquee.style.left=parseInt(marqueewidth)+8+"px"
}
else if (document.layers){
if (ns_marquee.left>(actualwidth*(-1)+8))
ns_marquee.left-=copyspeed
else
ns_marquee.left=parseInt(marqueewidth)+8
}
}
if (iedom||document.layers){
with (document){
document.write('<table border="0" cellspacing="0" cellpadding="0"><td>')
if (iedom){
write('<div style="position:relative;width:'+marqueewidth+';height:'+marqueeheight+';overflow:hidden">')
write('<div style="position:absolute;width:'+marqueewidth+';height:'+marqueeheight+';background-color:'+marqueebgcolor+'" onMouseover="copyspeed=pausespeed" onMouseout="copyspeed=marqueespeed">')
write('<div id="iemarquee" style="position:absolute;left:0px;top:0px"></div>')
write('</div></div>')
}
else if (document.layers){
write('<ilayer width='+marqueewidth+' height='+marqueeheight+' name="ns_marquee" bgColor='+marqueebgcolor+'>')
write('<layer name="ns_marquee2" left=0 top=0 onMouseover="copyspeed=pausespeed" onMouseout="copyspeed=marqueespeed"></layer>')
write('</ilayer>')
}
document.write('</td></table>')
}
}
</script>
However when i try to put my php code in and it doesn't work. Ok some of you will say that PHP and Javascript are not compatible, but i'm interested in either a direct solution or a work around.
Or if you can get javascript to access mysql database even better (not too sure on that)
Is there any chance that one of you can find some way of putting php into this var marqueecontent='<nobr><font face="Arial"><h3>PHP HERE</h3></font></nobr>' because if tried all different types of this and none of them work with my mootols version and even mootools ones dont work.
Any help would be greatly and warmly welcomed.
Thanks
UPDATE
I have tried echoing inside the javascipt and it is just blank, the one thing as you have said i haven't tried using php to echo the whole javascript
Your own solution isn't very clean, and it has several bugs. You should do this instead:
<?php
$newsContent = '';
while ($row = mysql_fetch_assoc($query))
{
if ($newsContent != '')
$newsContent .= ', ';
$newsContent .= htmlspecialchars($row['news_content']);
}
?>
<script language="JavaScript1.2">
var marqueewidth="780px"
var marqueeheight="50px"
var marqueespeed=2
var marqueebgcolor=""
var pauseit=1
//Keep all content on ONE line, and backslash any single quotations (ie: that\'s great):'
var marqueecontent='<nobr><font face="Arial"><h3><?php echo addslashes($newsContent); ?></h3></font></nobr>'
////NO NEED TO EDIT BELOW THIS LINE////////////
...
Using your example: marqueecontent='<nobr><font face="Arial"><h3>PHP HERE</h3></font></nobr>' it should look something like this
marqueecontent='<nobr><font face="Arial"><h3><?php echo "Hello From PHP"; ?></h3></font></nobr>'
Keep in mind that for PHP to pass any data o JavaScipr it must be echoed from PHP.
Thank you for your helpful comments as a result this is the solution i have found myself:
Using php to echo the javascript:
<?php echo'<script language="JavaScript1.2">
var marqueewidth="780px"
var marqueeheight="50px"
var marqueespeed=2
var marqueebgcolor=""
var pauseit=1
//Keep all content on ONE line, and backslash any single quotations (ie: that\'s great):'
?>
var marqueecontent='<nobr><font face="Arial"><h3><?php while($row = mysql_fetch_assoc($query)){ echo $row['news_content'];}?></h3></font></nobr>'
////NO NEED TO EDIT BELOW THIS LINE////////////
marqueespeed=(document.all)? marqueespeed : Math.max(1, marqueespeed-1) //slow speed down by 1 for NS
var copyspeed=marqueespeed
var pausespeed=(pauseit==0)? copyspeed: 0
var iedom=document.all||document.getElementById
if (iedom)
document.write('<span id="temp" style="visibility:hidden;position:absolute;top:-100px;left:-9000px">'+marqueecontent+'</span>')
var actualwidth=''
var cross_marquee, ns_marquee
function populate(){
if (iedom){
cross_marquee=document.getElementById? document.getElementById("iemarquee") : document.all.iemarquee
cross_marquee.style.left=parseInt(marqueewidth)+8+"px"
cross_marquee.innerHTML=marqueecontent
actualwidth=document.all? temp.offsetWidth : document.getElementById("temp").offsetWidth
}
else if (document.layers){
ns_marquee=document.ns_marquee.document.ns_marquee2
ns_marquee.left=parseInt(marqueewidth)+8
ns_marquee.document.write(marqueecontent)
ns_marquee.document.close()
actualwidth=ns_marquee.document.width
}
lefttime=setInterval("scrollmarquee()",20)
}
window.onload=populate
function scrollmarquee(){
if (iedom){
if (parseInt(cross_marquee.style.left)>(actualwidth*(-1)+8))
cross_marquee.style.left=parseInt(cross_marquee.style.left)-copyspeed+"px"
else
cross_marquee.style.left=parseInt(marqueewidth)+8+"px"
}
else if (document.layers){
if (ns_marquee.left>(actualwidth*(-1)+8))
ns_marquee.left-=copyspeed
else
ns_marquee.left=parseInt(marqueewidth)+8
}
}
if (iedom||document.layers){
with (document){
document.write('<table border="0" cellspacing="0" cellpadding="0"><td>')
if (iedom){
write('<div style="position:relative;width:'+marqueewidth+';height:'+marqueeheight+';overflow:hidden">')
write('<div style="position:absolute;width:'+marqueewidth+';height:'+marqueeheight+';background-color:'+marqueebgcolor+'" onMouseover="copyspeed=pausespeed" onMouseout="copyspeed=marqueespeed">')
write('<div id="iemarquee" style="position:absolute;left:0px;top:0px"></div>')
write('</div></div>')
}
else if (document.layers){
write('<ilayer width='+marqueewidth+' height='+marqueeheight+' name="ns_marquee" bgColor='+marqueebgcolor+'>')
write('<layer name="ns_marquee2" left=0 top=0 onMouseover="copyspeed=pausespeed" onMouseout="copyspeed=marqueespeed"></layer>')
write('</ilayer>')
}
document.write('</td></table>')
}
}
</script>
Thanks Again!!
Related
How can I give the ID value to Javascript in same page.
Example data :
<a href="" id="ctextarea<?php echo $uid; ?>"/>
JS :
function recountss()
{
var maxlen=280;
var current = maxlen-$('#ctextarea').val().length;
$('.counters').html(current);
if(current<0 || current==maxlen)
{
$('.counters').css('color','#D40D12');
$('input.comment_button').attr('disabled','disabled').addClass('inact');
}
else if (!$.trim($("#ctextarea").val())) {
$('input.comment_button').attr('disabled','disabled').addClass('inact');
}
else
$('input.comment_button').removeAttr('disabled').removeClass('inact');
if(current<10)
$('.counters').css('color','#D40D12');
else if(current<20)
$('.counters').css('color','#5C0002');
else
$('.counters').css('color','#C0C0C0');
}
I tried using get class, but it's effect for 1 data not for many data.
Have idea ?
Thanks.
This should work :
<script type="text/javascript">
var id = "ctextarea<?php echo $uid; ?>";
</script>
In your javascript, you can do :
var current = maxlen-$(id).val().length;
But you should use an other name for your variable.
Try data- attributes:
Link
In JS you can do the following:
document.getElementById('link').getAttribute('data-id');
This stuff is perfectly valid in HTML5 - but even older browsers just don't care.
I have a piece of javascript code that causes a text box to appear adjacent to a drop-down menu when a certain selection is made. It worked perfectly until I embedded it in html. I'm not sure why it's not working now, although it's probably really trivial.
Here is the function, as it is now:
$public->html .= '<script type="text/javascript">;
$(function(){
// initially check the default value in dd_question
if($("#dd_question").find("option:selected").val() == "0"){
$("#other_question").show();
}else{
$("#other_question").hide();
}
$("#dd_question").change(function() {
if($(this).find("option:selected").val() == "0"){
$("#other_question").show();
}else{
$("#other_question").hide();
}
});
});
</script>';
It would be great to have this working again. Can anyone see why it's not?
I'm not php user but i can tell you that the semi colon at this line probably shouldn't be there.
$public->html .= '<script type="text/javascript">;
Waste of code
<script type="text/javascript">
$(function() {
$("#dd_question").change(function() {
var show = $(this).val() == "0";
if (show) $("#other_question").show();
else $("#other_question").hide();
}).change();
});
</script>
I have a datatable that I am attempting to put drill-downs into based on the output of a php file, but I am having a few issues I can't seem to figure out. I am using http://datatables.net/blog/Drill-down_rows as a guide. So far this is my code:
Javascript:
<script type="text/javascript">
$("tr").live("click", function(){
var nTr = this;
var i = $.inArray(nTr, anOpen);
//oTable = my datatable
var oData = oTable.fnGetData(nTr);
if(i === -1) {
$(this).addClass('row_selected');
//THIS IS WHERE I AM GETTING A LITTLE LOST
//I WANT THE VALUE OF response.details TO BE STORED IN nDetailsRow
//oData.url is a mDataProp stored in the datatable row that contains the PHP link (this works okay)
var nDetailsRow = $.get(oData.url, function(response) {
//I don't really understand exactly what this is doing... but response.details is what I want to display from PHP
oTable.fnOpen(nTr, response.details, 'details');
});
//THIS LINE DOES NOT WORK CORRECTLY BECAUSE nDetailsRow IS NOT WHAT I WANT IT TO BE
$('div.innerDetails', nDetailsRow).slideDown();
anOpen.push(nTr);
else {
...
}
}
</script>
PHP:
<?PHP
$tableOut = '<div class="innerDetails">
<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">
<tr><td>Test Cell:</td><td>This is a test</td></tr>
</table>
</div>';
$data = array();
$data['details'] = $tableOut;
echo json_encode($data);
?>
I feel like I am almost there, but I don't quite understand the ajax $.get and am not sure if I am actually getting the JSON correctly from the PHP file. I also don't quite understand how to store that JSON in the active jquery code. Any ideas on how to accomplish these tasks and how to get my drill-down to display the PHP JSON data response.details?
I figured it out almost immediately after posting, I needed to use $.getJSON and include the last two lines inside that function. I am now using the following code which appears to work correctly:
<script type="text/javascript">
$(document).on("click", "tr", function(){
var nTr = this;
var i = $.inArray(nTr, anOpen);
//oTable = my datatable & oData.url is the mDataProp link to the PHP page
var oData = oTable.fnGetData(nTr);
if(i === -1) {
$(this).addClass('row_selected');
$.get(oData.url, function(response) {
oTable.fnOpen(nTr, response.details, 'details');
$('div.innerDetails', response.details).slideDown();
anOpen.push(nTr);
});
else {
...
}
}
</script>
Edit: Added/changed code from suggestions
<script type="text/javascript">
$("tr").live("click", function(){
var nTr = this;
var i = $.inArray(nTr, anOpen);
//oTable = my datatable
var oData = oTable.fnGetData(nTr);
if(i === -1) {
$(this).addClass('row_selected');
//THIS IS WHERE I AM GETTING A LITTLE LOST
//I WANT THE VALUE OF response.details TO BE STORED IN nDetailsRow
//oData.url is a mDataProp stored in the datatable row that contains the PHP link (this works okay)
var nDetailsRow = $.get(oData.url, function(response) {
try{
eval(response);
delete response;
//I don't really understand exactly what this is doing... but response.details is what I want to display from PHP
oTable.fnOpen(nTr, req.details, 'details');
}catch(e){
// error
}
});
//THIS LINE DOES NOT WORK CORRECTLY BECAUSE nDetailsRow IS NOT WHAT I WANT IT TO BE
$('div.innerDetails', nDetailsRow).slideDown();
anOpen.push(nTr);
else {
...
}
}
</script>
PHP:
var req = { details : '<?php echo str_replace('%', '\\x', urlencode('
<div class="innerDetails">
<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">
<tr>
<td>Test Cell:</td>
<td>This is a test</td>
</tr>
</table>
</div>')); ?>' };
I have several divs that a user can Minimize or Expand using the jquery toggle mothod. However, when the page is refreshed the Divs go back to their default state. Is their a way to have browser remember the last state of the div?
For example, if I expand a div with an ID of "my_div", then click on something else on the page, then come back to the original page, I want "my_div" to remain expanded.
I was thinking it would be possible to use session variables for this, perhaps when the user clicks on the expand/minimize button a AJAX request can be sent and toggle a session variable...IDK..any ideas?
There's no need for an ajax request, just store the information in a cookie or in the localstorage.
Here's a library which should help you out: http://www.jstorage.info/
Some sample code (untested):
// stores the toggled position
$('#my_div').click(function() {
$('#my_div').toggle();
$.jStorage.set('my_div', $('#my_div:visible').length);
});
// on page load restores all elements to old position
$(function() {
var elems = $.jStorage.index();
for (var i = 0, l = elems.length; i < l; i++) {
$.jStorage.get(i) ? $('#' + i).show() : hide();
}
});
If you don't need to support old browsers, you can use html5 web storage.
You can do things like this (example taken from w3schools):
The following example counts the number of times a user has visited a
page, in the current session:
<script type="text/javascript">
if (sessionStorage.pagecount) {
sessionStorage.pagecount=Number(sessionStorage.pagecount) +1;
}
else {
sessionStorage.pagecount=1;
}
document.write("Visits "+sessionStorage.pagecount+" time(s) this session.");
</script>
Others have already given valid answers related to cookies and the local storage API, but based on your comment on the question, here's how you would attach a click event handler to a link:
$("#someLinkId").click(function() {
$.post("somewhere.php", function() {
//Done!
});
});
The event handler function will run whenever the element it is attached to is clicked. Inside the event handler, you can run whatever code you like. In this example, a POST request is fired to somewhere.php.
I had something like this and I used cookies based on which user logged in
if you want only the main div don't use the
$('#'+div_id).next().css('display','none');
use
$('#'+div_id).css('display','none');
*Here is the code *
//this is the div
<div id = "<?php echo $user; ?>1" onclick="setCookie(this.id)" ><div>My Content this will hide/show</div></div>
function setCookie(div_id)
{
var value = '';
var x = document.getElementById(div_id);
var x = $('#'+div_id).next().css('display');
if(x == 'none')
{
value = 'block';
}
else
{
value = 'none';
}
console.log(div_id+"="+value+"; expires=15/02/2012 00:00:00;path=/")
//alert(x);
document.cookie = div_id+"="+value+"; expires=15/02/2012 00:00:00;path=/";
}
function getCookie(div_id)
{
console.log( div_id );
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==div_id)
{
return unescape(y);
}
}
}
function set_status()
{
var div_id = '';
for(var i = 1; i <= 9 ; i++)
{
div_id = '<?php echo $user; ?>'+i;
if(getCookie(div_id) == 'none')
{
$('#'+div_id).next().css('display','none');
}
else if(getCookie(div_id) == 'block')
{
$('#'+div_id).next().slideDown();
}
}
}
$(document).ready(function(){
get_status();
});
Look about the JavaScript Cookie Method, you can save the current states of the divs, and restore it if the User comes back on the Site.
There is a nice jQuery Plugin for handling Cookies (http://plugins.jquery.com/project/Cookie)
Hope it helps
Ended up using this. Great Tutorial.
http://www.shopdev.co.uk/blog/cookies-with-jquery-designing-collapsible-layouts/
I am have a table that shows the user suggestions that they have recieved on clicking read more some ajax is fired and in the database the suggestion is marked as read. Currently if the suggestion is new I show a closed envelope, if it is read I show an open envelope, however I can get it to reload the table when the user clicks the read more link so that the new class can be added. Currently it half works, they click read more and the full suggestions fades in but I need the envelope to change also.
<table>
<?php
$colours = array("#f9f9f9", "#f3f3f3"); $count = 0;
if(isset($newSuggestions)) {
foreach($newSuggestions as $row) {
if($row['commentRead'] == 0) {
$newRow = "new";
} else {
$newRow = "old";
}
?>
<tr id="a<?=$row['thoughtId'];?>" bgcolor="<?php echo $colours[$count++ % count($colours)];?>">
<?php
echo "<td class='".$newRow."'>".substr($row['thought'], 0,50)."...</td>";
echo "<td class='read'><a href='".base_url()."thought/readSuggestion/".$row['thoughtId']."' class='readMore'>Read More</a>";
echo "</tr>";
}
} else {
echo "You have no new suggestions";
}
?>
</table>
</div><!--/popular-->
</div><!--/widget-->
<div id="readMore">
</div>
<script type="text/javascript">
$(document).ready(function() {
//alert("hello");
$('#tabvanilla').tabs({ fx: { opacity: 'toggle', height:'toggle' } });
$('a.readMore').click(function(){
$('#readMore').fadeIn(500);
var url = $(this).attr('href');
$.ajax({
url : url,
type : "POST",
success : function(html) {
$('#readMore').html(html)
},
complete : function(html) {
$('table').html()
}
});
return false;
});
});
</script>
In the JavaScript where you open/fill in the full suggestions, you can modify the envelope image as well, using something like:
$('#envelope').attr('src', 'src/to/envelope.png');
I see no img tags, so you need to add one and fill in the id, so it is found by the JavaScript.
BTW: Having HTML and PHP on the same lines/parts, makes the total very unreadable. Only use <?php ... ?> for large PHP code blocks, otherwise use echo (or something similar).