Display popup when class elements are clicked using javascript - javascript

So I am trying to get this code to echo my popup when class elements are clicked. I have the code in the head section of my wordpress file but it's not working. Any ideas?
I've even tried moving the variable around and still nothing
<?php
function popCash() {
$doit = "<script type='text/javascript'>
var wid = '111111';
var uid = '111111';
</script>
<script type='text/javascript' src='//cdn.popcash.net/pop.js'></script>";
echo $doit;
}
?>
<script type='text/javascript'>
$(document).ready(function(){
$('.post-thumbnail, .thumb-block, .display-img').click(function(){
var <?php echo popCash;?>
});
});
</script>
I need it to show the popup when the class elements are clicked

Depending on what kind of result you want, you need to use console.log(popCash) or alert(popCash), not echo, which is not valid JavaScript.
Follow-up after comment:
If you're trying to execute that script, it's more like document.write(popCash) that you'd be looking for, but this wouldn't be a very efficient way to accomplish what you're trying to do because you'd be loading up that script every single time you got a click, and accumulating additional <script> elements with every click.
For one thing, it looks like you're assigning values to global variables wid and uid using a script. There's absolutely no good reason to create a new script just to do that. Simply assign the variable directly:
<script type='text/javascript'>
var wid;
var uid;
$(document).ready(function(){
$('.post-thumbnail, .thumb-block, .display-img').click(function(){
wid = '111111';
uid = '111111';
var popCash = "<script type='text/javascript' src='//cdn.popcash.net/pop.js'>\n"+
"<\/script>";
document.write(popCash);
});
});
</script>
But then the question becomes: "Why reload the 'cdn.popcash.net' for every click?"
Isn't there a method inside the script that can be called whenever it needs to be invoked again?
And even if the script is so poorly written that it must be run from the top for every invocation (that's a terrible API!), you can at least dynamically create and delete script tags to do the job instead of using document.write(), but that would take a bit more explaining to describe.

Related

Call Javascript Function from PHP in a loop

I have been looking at answers to this across the web for about an hour now, and trying things based on those answers (I know this kind of issue comes up often). However, nothing I am trying is working. So an explanation first:
I am looping through a table in PHP (in a while loop), and need to call a JavaScript function for each record in the row set returned for my table. To try to get started, I have a super basic function that just lets me know I called it ... it's not working. Here's the PHP code (the reason for the DIV tag is that I eventually want to replace the innerHTML of the DIV from the JS code I know how to do that and have done so elsewhere ...):
// the loop:
while( $row = mysqli_fetch_array( $heralds_result ) )
{
$herald_id = $row["roster_id"];
$sca_name = $row["sca_name"];
// create a div for each herald as we go with its' own name (using id ...)
echo " <div id='" . $herald_id . "'>\n";
echo " " . $sca_name . "\n";
echo " <script type='text/javascript'>test();</script>\n";
echo " </div>\n";
}
This is the JavaScript code (at the bottom of the file):
<script type="text/javascript">
function test()
{
alert( "Test function" );
}
</script>
However, I get no "alert" dialog, just the text streamed out. So for the first row I get:
<div id='1'>
Aasa Thorvaldsdoittr
<script type='text/javascript'>test();</script>
</div>
As the alert dialog is not displayed, it tells me the Javascript function is not being called, or there is some error that is truly not obvious to me after staring at it for a long time. This is something that shouldn't be this difficult, I am sure I have some really obvious error that someone will see as soon as they look at the code, but it's evading me completely.
"JavaScript code at the bottom of the file"
is the problem. Scripts are run as soon as they are added to the DOM. Things are added to the DOM in the order they are given in the HTML.
Therefore the script tags which try to call your function are added - and executed - before the script tag which actually contains the function gets added. So they try to execute a function which doesn't yet exist. If you look in your browser's Console (in the Developer Tools) you probably have some errors complaining about this.
The simple solution is to declare the script tag containing the function somewhere in your HTML before the code which tries to use it.
As an aside, it would be interesting to know what you plan to do with this function in reality - consider whether you could achieve the same effect directly by creating some markup using PHP, rather than firing off lots of JS while the page is loading.
You should move the function declaration upper than it used. For example:
<script type="text/javascript">
function test()
{
alert( "Test function" );
}
</script>
..
<?php
..
// your loop
..
?>
or
<?php
..
echo '<script type="text/javascript">
function test()
{
alert( "Test function" );
}
</script>';
..
// your loop
..
?>

Calling JS function from PHP not working

Using a method recommended by a user in a previous question I used just one document (index.php) to show different contents instead of creating one file for each one.
This is the code:
HTML
Home
More info
Contact Us
<div id="index">...index content...</div>
<div id="more_info">...more info content...</div>
JS
$(document).ready(function(){
function more_info(){
$('#index').hide();
$('#more_info').show();
}
});
PHP
<?php
if (isset($_GET['id_page'])) {
$id = $_GET['id_page'];
if ($id == 1) {
?>
<script>
more_info();
</script>
<?php
}
}
?>
That's not working. But if I change <script> more_info(); </script> for:
<script>
$(document).ready(function(){
$('#index').hide();
$('#quienes-somos').show();
});
</script>
It works. Why is this?
It looks like the problem you are having is because you are defining your more_info function inside of a function. This takes it out of the global scope which will not make that function accessible anywhere except for inside of your document ready function.
//more_info is now available globally
function more_info(){
$('#index').hide();
$('#more_info').show();
}
$(document).ready(function(){
//document ready code here
});
This should make the more_info execute when you output the JS function from PHP. Also it is good to note that since you are not executing the function on ready you will need to make sure the html is available for the JS to modify it. It is normally best practice to put all your JS just before the closing tag. This will ensure your html loads as quickly as possible and your JS will always have access to the HTML you are attempting to edit. With the JS in the head tag you need to make sure your JS is being called at the correct time using:
$(function() {
});
OR
$(document).ready(function() {
});
OR
$(window).load(function() {
});
All of these methods execute at different times during page initialization. With JS in the head tag your browser will need to download all the JS to the client before it can begin to render the HTML which will also add to time between going to the site and actually seeing the site.

Initialize more than one html element using jQuery and Javascript

I have tried to lead my html element to fire my customized JS file's method.
Third textarea appears nicely.
First and second textareas does not effect any of the settings i am trying to change in myJSFile.js file.
Here's my problem : js file loads the last textarea nicely, but cannot initialize previous ones properly using my js methods.
I'm doing something wrong with my JS file, and i'd appreciate if you help me.
P.S. : Initalizing some plugin and working on CKEditor.
Here's my HTML file :
<textarea id="myTextAreaID" name="myTextArea"></textarea>
<script type="text/javascript" src="../public/js/myJSFile.js"onload="setTextAreaValues('myTextAreaID')"></script>
<textarea id="myTextAreaID2" name="myTextArea2"></textarea>
<script type="text/javascript" src="../public/js/myJSFile.js"onload="setTextAreaValues('myTextAreaID2')"></script>
<textarea id="myTextAreaID3" name="myTextArea3"></textarea>
<script type="text/javascript" src="../public/js/myJSFile.js"onload="setTextAreaValues('myTextAreaID3')"></script>
Here's myJSFile.js file
var textAreaID;
$(function(){
var myTextArea = $('#'+textAreaID);
//something is being loaded here, and it is loaded fine.
});
function setTextAreaParameters(param){
textAreaID = param;
}
Thanks in advance.
This is not very good idea to do it like this, however it's interesting to understand why it happens. In your code below you are defining global variable textAreaID:
var textAreaID;
$(function() {
var myTextArea = $('#' + textAreaID);
//something is being loaded here, and it is loaded fine.
});
function setTextAreaParameters(param) {
textAreaID = param;
}
This script is injected three times into document. After the last script tag the value of textAreaID variable will be myTextAreaID3, because it's global and the last setTextAreaParameters invocation will override previous. Remember that scripts are loaded synchronously in your case (no async or deferred attribute), it means that onload callbacks don't wait and immediately set textAreaID to new values.
However DOMContentLoaded event has not yet fired. This is the event you are subscribing with this code:
$(function() {
// DOMContentLoaded
});
When it eventually does - only the third textarea will be processed - the one with id myTextAreaID3.
Better approach would be to have only one script tag and set textareas the same className attribute:
<textarea id="myTextAreaID2" name="myTextArea2" class="editor"></textarea>
Then in the script probably have some sort of map with configuration parameters for each individual textarea.
You are including the same script three times, but the browser is probably smart enough to only load it once (no reason to load the same script on the same page more than once).
What you need to do is to include the script only once, say before the end of the body tag
...
<script type="text/javascript" src="../public/js/myJSFile.js"></script>
</body>
and then in the JS file, wait for the document to load, and handle all text areas accordingly:
$(function() {
$('textarea').each(function(i, j) {
console.log('do something for the ' + i + 'th text area');
});
})

Javascript element tag name undefined

So I'm not that great with Javascript so I'll put that forward right away. That being said, I've looked up as much as I could on this particular problem before asking, but the suggestions haven't solved my issues. I'm ultimately trying to pull all of the links from an iframe window on the same domain as the main page. Then I want to basically search that link array to match it with the current page to trigger a CSS modification to the html code (this part is not coded yet, FYI). So here is the part I have so far: Side note: The confirms are in there to debug the code and try to tell me where it's failing and what my queries are returning, they won't stay obviously when this is finished. I appreciate any advice that may help me fix this!
<script type="text/javascript">
// main is the iframe that I'm trying to search for a tags
document.getElementById("main").onload = function() {
confirm("test");
var main = document.getElementById("main");
var anchors = main.contentWindow.document.getElementsByTagName('a');
confirm(anchors[1]);
for (var i in anchors) {
confirm(anchors[i].getAttribute("href"));
}
};
</script>
I have created a plunker for you its working. I think its the placement of code in your file is causing the problem.
<iframe id="main" src="content_if.html"></iframe>
<script>
// main is the iframe that I'm trying to search for a tags
document.getElementById("main").onload = function() {
confirm("test");
var main = document.getElementById("main");
var anchors = main.contentWindow.document.getElementsByTagName('a');
confirm(anchors[1]);
for (var i in anchors) {
confirm(anchors[i].getAttribute("href"));
}
};
</script>
You should use jQuery to do this in a cross browser way. Include jQuery in page
<script src="https://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
and follow this post
There is a similar post about doing this and I agree with Mohamed-Yousef. If you can use jquery then you should do so!
$("#main").contents().find("a").each(function(element) {
// "each" will iterate through every a tag and inject them as the "element" argument
// visible in the scope of this anonymous function
});
EDIT:
You must include
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
above your code that references the $ variable. There are other ways to use jQuery but this is probably the easiest.

How to dynamically insert a <script> tag via jQuery after page load?

I'm having problems getting this to work. I first tried setting my script tags as strings and then using jquery replaceWith() to add them to the document after page load:
var a = '<script type="text/javascript">some script here</script>';
$('#someelement').replaceWith(a);
But I got string literal errors on that var. I then tried encoding the string like:
var a = '&left;script type="text/javascript">some script here<\/script>';
but sending that to replaceWith() outputs just that string to the browser.
Can someone please let me know how you would go about dynamically adding a <script> tag into the browser after page load, ideally via jQuery?
You can put the script into a separate file, then use $.getScript to load and run it.
Example:
$.getScript("test.js", function(){
alert("Running test.js");
});
Try the following:
<script type="text/javascript">
// Use any event to append the code
$(document).ready(function()
{
var s = document.createElement("script");
s.type = "text/javascript";
s.src = "http://scriptlocation/das.js";
// Use any selector
$("head").append(s);
});
http://api.jquery.com/append
Here's the correct way to do it with modern (2014) JQuery:
$(function () {
$('<script>')
.attr('type', 'text/javascript')
.text('some script here')
.appendTo('head');
})
or if you really want to replace a div you could do:
$(function () {
$('<script>')
.attr('type', 'text/javascript')
.text('some script here')
.replaceAll('#someelement');
});
A simpler way is:
$('head').append('<script type="text/javascript" src="your.js"></script>');
You can also use this form to load css.
This answer is technically similar or equal to what jcoffland answered.
I just added a query to detect if a script is already present or not.
I need this because I work in an intranet website with a couple of modules, of which some are sharing scripts or bring their own, but these scripts do not need to be loaded everytime again. I am using this snippet since more than a year in production environment, it works like a charme. Commenting to myself: Yes I know, it would be more correct to ask if a function exists... :-)
if (!$('head > script[src="js/jquery.searchable.min.js"]').length) {
$('head').append($('<script />').attr('src','js/jquery.searchable.min.js'));
}
Here is a much clearer way — no need for jQuery — which adds a script as the last child of <body>:
document.body.innerHTML +='<script src="mycdn.js"><\/script>'
But if you want to add and load scripts use Rocket Hazmat's method.
Example:
var a = '<script type="text/javascript">some script here</script>';
$('#someelement').replaceWith(a);
It should work. I tried it; same outcome. But when I used this:
var length = 1;
var html = "";
for (var i = 0; i < length; i++) {
html += '<div id="codeSnippet"></div>';
html += '<script type="text/javascript">';
html += 'your script here';
html += '</script>';
}
$('#someElement').replaceWith(a);
This worked for me.
Edit: I forgot the #someelement (btw I might want to use #someElement because of conventions)
The most important thing here is the += so the html is added and not replaced.
Leave a comment if it didn't work. I'd like to help you out!
There is one workaround that sounds more like a hack and I agree it's not the most elegant way of doing it, but works 100%:
Say your AJAX response is something like
<b>some html</b>
<script>alert("and some javscript")
Note that I've skipped the closing tag on purpose. Then in the script that loads the above, do the following:
$.ajax({
url: "path/to/return/the-above-js+html.php",
success: function(newhtml){
newhtml += "<";
newhtml += "/script>";
$("head").append(newhtml);
}
});
Just don't ask me why :-) This is one of those things I've come to as a result of desperate almost random trials and fails.
I have no complete suggestions on how it works, but interestingly enough, it will NOT work if you append the closing tag in one line.
In times like these, I feel like I've successfully divided by zero.
If you are trying to run some dynamically generated JavaScript, you would be slightly better off by using eval. However, JavaScript is such a dynamic language that you really should not have a need for that.
If the script is static, then Rocket's getScript-suggestion is the way to go.

Categories