PDA

View Full Version : javascript dont work inside new content of divs generated by Ajax



xpolhecx
07-20-2008, 04:31 PM
I'm learning Ajax and dont understand why Javascript dont work inside new DIVs, generated by Ajax (i get variables through GET methods). Javascript works only on "first page". When content of some DIV is replaced, javascript dont work anymore. Please help me, here is my example code.


<head>
<script type="text/javascript">

function disableSelectText(target){
if (typeof target.onselectstart!="undefined")
target.onselectstart=function(){return false}
else if (typeof target.style.MozUserSelect!="undefined")
target.style.MozUserSelect="none"
else
target.onmousedown=function(){return false}

target.style.cursor = "default"
}


function show(id){
var xmlHttp1;
try {xmlHttp1=new XMLHttpRequest();}catch (e){try{xmlHttp1=new ActiveXObject("Msxml2.XMLHTTP");}
catch (e){try{xmlHttp1=new ActiveXObject("Microsoft.XMLHTTP");}
catch (e){alert("Error");return false;}}}

xmlHttp1.onreadystatechange = function(){
if(xmlHttp1.readyState==4){
document.getElementById("content").innerHTML=xmlHttp1.responseText;
}
}

xmlHttp1.open("GET","http://localhost/prvaliga/test.php?content="+id,true);
xmlHttp1.send(null);
}



</script>
</head>





<body>

<?php
if ( isset($_GET['content']) ) {
if ($_GET['content'] == '1') {
?>
<div id="test1">Here is first content... You can select this text, <span style="color:#FF0000; font-weight:bold;">because javascript inside this DIV dont work</span> and i dont know why?</div><br />

<script type="text/javascript">
var somediv=document.getElementById("test1")
disableSelectText(somediv)
</script>
<?php
}
}
else {
?>

<div id="test">You cant select this text, <span style="color:#33CC33; font-weight:bold;">because javascript WORKS here</span></div><br />

<script type="text/javascript">
var somediv=document.getElementById("test")
disableSelectText(somediv)
</script>




<span style="cursor:pointer;" onclick="show(1)">First Content - Click here to show content</span><br /><br><br>

<?php } ?>

<div id="content"></div>

</body>

TheJoshMan
07-20-2008, 05:12 PM
I'm only seeing the problem in FF3. Works fine in IE7

xpolhecx
07-20-2008, 05:19 PM
Ajax is OK, but javascript dont work:

<div id="test1">Here is first content... You can select this text, <span style="color:#FF0000; font-weight:bold;">because javascript inside this DIV dont work</span> and i dont know why?</div><br />

<script type="text/javascript">
var somediv=document.getElementById("test1")
disableSelectText(somediv)
</script>

I can select this text, this means function disableSelectText(somediv) dont work.

TheJoshMan
07-20-2008, 05:52 PM
That's what I was saying, I can't select the text in either of the divs when viewing it in IE, it's only in FF that I see the problem. I'm not sure how to solve it though.