This question already has answers here:
Javascript in a wordpress page
(2 answers)
Closed 8 years ago.
When I call this code, it does not work.
<script language="javascript">
var l1OK_WC = false;
var l2OK_WC = false;
function share()
{
alert('yo');
}
function getIt_wc()
{
if(l1OK_WC && 120k_WC)
window.open('http://google.ca','_self');
if(!l1OK_WC)
alert("Message 1");
else if(!l2OK_WC)
alert("Message 2");
}
</script>
And this in the html.
<a class="Style3" href="javascript:getIt_wc();"><img src="http://i.imgur.com/XJy0nEq.png" /></a>
When I click the button, no message appears. This script works fine in blogger or html sites, but not on wordpress. I am doing this on a wordpress page.
Thank you.
EDIT: After looking at the source code of the page, you are naming the function incorrectly!
Your function shows on the page as:
function get()
{
if(l1OK_WC && l2OK_WC)
window.open('http://google.ca','_self');</p>
<p> if(!l1OK_WC)
alert("message 1 (You can enter any message)");
else if(!l2OK_WC)
alert("message 2(You can enter any message)");
}
You'll notice two errors:
It's named get() not getIt_wc(), so you're calling the wrong function in your onclick
You have some HTML code in there as well: && and <p> and </p>
ORIGINAL POST:
You don't need the a tag at all. Just use onclick on the image and remove the a tag:
<img class="Style3" src="http://i.imgur.com/XJy0nEq.png" onclick="getIt_wc()" />
To let people know it's clickable, in your stylesheet, add the cursor style to Style3:
.Style3 {
cursor: pointer;
}
Cant work. If you call the method getIt_wc, the variable l1OK_WC is ever call false.
You script are confusing and can't never produce a result.
Related
I need a Google AdWords conversion script to work whenever someone submits a form for a free quote. Google has provided the script which I'm put into a Snippet with WordPress and activated it for the site.
I now need to call that function when the submit button is pressed, but I can't remember the correct syntax and Google searches so far have led me down long paths of .php file creations that isn't answering what feels like a simple solution would solve.
Currently I have added the function in line with the existing code for the submit, but I'm not convinced this is correct. The below code is on the contact form that the page uses.
[submit id:submit class:btn class:btn-primary gtag_report_conversion() "Send"]
Below is the code I put into the Snippet minus the full "send to" AW address:
<script>
function gtag_report_conversion(url) {
var callback = function () {
if (typeof(url) != 'undefined') {
window.location = url;
}
};
gtag('event', 'conversion', {
'send_to': 'AW-.....',
'event_callback': callback
});
return false;
}
</script>
Depending on how that shortcode was implemented, odds are you can't just add inline event handlers to it like that - and without seeing the source code it's hard to determine (but I'd wager that it's most likely the case).
Just add this in the old fashioned way with the onclick or onsubmit event handler. I'd recommend the onsubmit since forms can be submitted without clicking on the button.
Since you've already loaded in your Script, you can just add to it:
<script>
function gtag_report_conversion(url){
var callback = function () {
if (typeof(url) != 'undefined') {
window.location = url;
}
};
gtag('event', 'conversion', {
'send_to': 'AW-.....',
'event_callback': callback
});
return false;
}
document.getElementById("your-form-id").onsubmit = function(){
gtag_report_conversion();
};
</script>
Just replace your-form-id with the id of your <form> element (not your submit button).
To prevent answers like: 'is the JavaScript file loaded?' -> Yes, it is loaded, at the footer part of the page! I have checked that with a simple message to the console, which is displayed!
But:
I've got a page with a button:
<button id="portfolio-posts-btn">Load portfolio related blog posts</button>
And a file main.js:
var portfolioPostsBtn = document.getElementById('portfolio-posts-btn');
var portfolioPostsContainer = document.getElementById("portfolio-posts-container");
if (portfolioPostsBtn) {
portfolioPostsBtn.addEventListener("click", function () {
console.log("the button was clicked!");
});
}
The text the button was clicked! should be displayed in the console, but it stays empty!
Apparently, the button click is not recognized, and thus, the var portfolioPostsBtn is false, or NULL... -> the method addEventListener() is not fired ?
I don't see the cause for this; I checked the spelling, should I use single or double quotes? Please help?
Thank you!
I've had this happen to me before, since theres two ways to do this I just used the other.
The first is onclick="function()", this is used as an attribute inside the element. Ex:
function clicked(){
alert("button clicked");
}
<button onclick="clicked();">Press me</button>
exaplaination: When you add this attribute to this element and I do believe some others when the button is clicked the specified code inside the quotes of the attibute will run. It doesn't have to be a number, e.g. onclick="alert(12+4/2);". But this is more of HTML than JavaScript using this version
The other way is using what you've got which (to me) is a lot more difficult then it needs to be. Heres my example
var b = document.getElementById("btn");
b.addEventListener("click", blogged);
function blogged(){
alert("this post has been blogged");
}
<button id="btn">Blog it</button>
This side of things has more to do with JavaScript and Event listeners. But the problem with you're code is that you're putting the event listener after you call the if statement. Here's my solution
var portfolioPostsBtn = document.getElementById('portfolio-posts-btn');
portfolioPostsBtn.addEventListener("click", function(){
check();
});
function check(){
if(portfolioPostsBtn){
console.log("posted");
}
}
<button id="portfolio-posts-btn">press this to post<button>
Presumably you have made a decision not to use jQuery. You'll need to wrap your code in an event listener so that the code is executed when the DOM is ready.
document.addEventListener("DOMContentLoaded", function(event) {
var portfolioPostsBtn = document.getElementById("portfolio-posts-btn");
var portfolioPostsContainer = document.getElementById("portfolio-posts-container");
if (portfolioPostsBtn) {
portfolioPostsBtn.addEventListener("click", function () {
console.log("the button was clicked!");
});
}
});
The answer is found in the uploading of the file page-portfolio.php!
I found out that the id="portfolio-posts-btn", added later, was not updated - could be my mistake, or the SFTP upload extension in Brackets - I did not see an error message!
Anyway, the issue is solved!
One more question: "are there methods to check if an id exists?". That could make live easier!
All contributors, thank you for your answers!
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have script that creates a div and adds a function that would remove this div on click, but it's not working.
function del(el) {
$("#"+el).remove();
}
function create() {
var element = document.createElement("div");
var att = document.createAttribute("onclick");
att.value = "del(this.id)";
element.setAttributeNode(att);
$(element).attr('id', "someID");
document.getElementById("someContainer").appendChild(element);
}
Yes, yes, I KNOW this is not the best way to add a function, but I want to do it this way.
Just FYI - after executing create() the DIV appears fine. I checked and it does have proper ID and onclick="del(this.id)" attribute, but after clicking on it nothing happens. I double checked and added alert("I'm working") to the onclick attribute later and that worked. I'm not getting any errors. In the past .remove() was working fine but now it doesn't (Maybe that's because of the way I'm adding a function this time)
EDIT: It appears that del() is not executed when clicking on div.
You have this posted with jQuery, but you're showing mostly Vanilla. As to your initial problem,
function del(el) {
$("#"+el).remove();
}
function create() {
var element = document.createElement("div");
var att = document.createAttribute("onclick");
att.value = "del(this.id)";
element.setAttributeNode(att);
$(element).attr('id', "someID");
document.getElementById("someContainer").appendChild(element);
$(element).html('<h1>DIV CREATED!</h1>').css('background-color', String.randColorHex());
}
create();
#someContainer > div { height: 10em; width: 100%; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://cdn.rawgit.com/JDMcKinstry/String.randColorHex/0c9bb2ff/String.randColorHex.js"></script>
<div id="someContainer"></div>
Seems to work fine.
My guess would be that you have an issue with creating multiple divs by with the same ID, or possibly a scope issue.
Here's a couple steps you might take to double check the issue if using Google Chrome Dev Tools:
Open Console
Double Check function 'del' is globally available and the method you expect it to be by simply typing del. If you get an error, then your method may be displaced.
Another way you could check would be put the following in your onClick: try{console.debug(del);}catch(err){console.error('DEL DOES NOT EXIST!')}
Once you've established the method is within scope, if still not working, try the following:
Replace $("#"+el).remove(); with console.debug(el, $('#'+el))
This does a couple of things: It shows you that the Function is working, as well as gives you information of what's going on within.
If the first part of the console message (el) is the ID you expect, then check the 2nd part ($('#'+el)).
It should look something like: [div:#someID]
Open it and check it's length'. If0`, then it did not find that element.
If 1, then remove should be working fine. Put remove back in just above this console call, and ensure you now get a length of 0
Just FYI, this is how to do what you're trying to do using jQuery.
function create() {
var container = $('#someContainer'), // get container
// create div, everything in {} is an ATTR, then append it TO the container
div = $('<div />', { id: 'someID' + container.children('div').length+1 }).appendTo(container);
// just for visual, i use my own plugin to set a random background color
div.css('background-color', String.randColorHex());
}
$(function() {
$(document) // your click methods
.on('click', '#btnCreate', create)
.on('click', '#someContainer > div', function(e) { $(this).remove(); })
// trigger button once on load
$('#btnCreate').trigger('click');
})
#someContainer > div { height: 2em; width: 100%; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://cdn.rawgit.com/JDMcKinstry/String.randColorHex/0c9bb2ff/String.randColorHex.js"></script>
<button id="btnCreate">Create</button>
<hr />
<div id="someContainer"></div>
This question already has an answer here:
jsFiddle: no connection between html and js? Can't call simple function from button? [duplicate]
(1 answer)
Closed 6 years ago.
I keep getting this error when i inspected the element of my button. The button is suppose to give a print view to page.
HTML Code:
<button class = "hidden-print" onclick = "printProducts()">Print Products</button>
Javascript Code:
function printProducts(){
window.print();
}
Attached here is my code live in jsFiddle:
https://jsfiddle.net/PochMendoza/scj0q0dk/
"In JSFiddle, when you set the wrapping to "onLoad" or "onDomready", the functions you define are only defined inside that block, and cannot be accessed by outside event handlers."
Easiest fix is to change:
function something(...)
To:
window.something = function(...)
---Niet The Dark Absol
For your example, you want to define the onclick method of a button. That's really easy with JavaScript, we just need to give the button an id in the HTML, so that we can find it in our JavaScript code.
Change this:
<button class = "hidden-print" onclick = "printProducts()">Print Products</button>
To this:
<button id="myButton" class="hidden-print">Print Products</button>
Note that we no longer need the onclick="printProducts()" part anymore.
Now we need to set the printProducts function to run when the button is clicked. This can be done like so:
document.getElementById('myButton').onclick = printProducts;
Start edit
This code needs to be placed in the onload function though, to properly run.
Do that like so:
window.onload = function() {
document.getElementById('myButton').onclick = printProducts;
}
End edit
And the printProducts function remains the same.
Working JSFiddle
document.getElementById('myButton').onclick = printProducts;
function printProducts(){
window.print();
}
<button id="myButton" class="hidden-print">Print Products</button>
I am looking for some assistance with calling a function after the first has been completed. I'm pretty new to jquery in general and am having some difficulty getting this to work.
The code below is what I have right now, which is currently working for just the 'slideonlyone' jquery plugin. What I would like to do is have the slideonlyone function work as usual and then once that reveals the div, i would like the page to scroll down (or up depending on placement) to the top of the div being revealed, since some of them are images and may show up awkwardly on the page.
<script type="text/javascript">
function slideonlyone(thechosenone) {
$('.newboxes2').each(function(index) {
if ($(this).attr("id") == thechosenone) {
$(this).slideDown(600);
}
else {
$(this).slideUp(600);
}
});
}
</script>
The HTML for the anchor tag looks like this...not sure if thats really needed though.
<a href="javascript:slideonlyone('newboxes11');">
<div class="project">
<img src="image.png" />
</div>
</a>
Please and thank you!
From the second example of .slideDown(), you would modify slideonlyone as follows
function slideonlyone(thechosenone, domeafter) {
var mdomeafter = function () {};
if (domeafter !== undefined && typeof domeafter === 'function') mdomeafter = domeafter;
$('.newboxes2').each(function(index) {
if ($(this).attr("id") == thechosenone) $(this).slideDown(600, mdomeafter);
else $(this).slideUp(600, mdomeafter);
});
}
and some function for domeafter as a second argument in your link.
I might be reading your question incorrectly, but if you want something to occur after the slideUp or slideDown animations finish then all you need to do is supply a call back function as a part of the call to slideUp/slideDown. So for example
$(this).slideDown(600, function() {
do something when slide down finishes
});
See http://api.jquery.com/slideUp/ for more info on the slideUp function.
check this JsFiddle Demo it's simple and maybe it will help you