Content of <script> printed instead of executed - javascript

Basically, I would like to know what could cause the content of a <script> tag to be printed instead of executed in HTML.
Context: I have accordion buttons, what I want to do is change the image in the button from a down arrow to an up arrow on click. I am using part of the code described here.
If i put my code in a fiddle, like this one (I replaced img with alts to avoid local files problems), it works.
However, in my code, if I put the script before the button, nothing happens, and if i put it after it, then the content of the script apears below the button when I click it (event if it's just var a = null, then it would print var a = null).
<button class="accordion" id="button_emotion">VIEWS<img id="button_emotion_img" src="images/arrow_grey.svg" width="30" height="30" alt="" style="float:right;margin:0 0px 0 0px;" /></button>
<script>
document.getElementById('button_emotion').onclick=function () {
document.getElementById('button_emotion_img').src = "images/arrow_grey_up.svg";
};
</script>
I have also tried using onClick="myFunction()" in the button tag with the same result.
What could be causing this?
UPDATE:
I have found the culprit. Later in the code, there is something like that:
<script>
var acc = document.getElementsByClassName("accordion");
var i;
for (i = 0; i < acc.length; i++) {
acc[i].onclick = function(){
this.classList.toggle("active");
this.nextElementSibling.classList.toggle("show");
}
}
</script>
I am not exactly sure what it does as I did not write this code, but it shows the next tags that are non "accordion" class. There is a modified bootstrap that makes it possible to print the content, however without it, it just doesn't execute the script, but does not print it either.
Here's the updated JSFiddle with the extra code. If you put the image changing part before the script or in a <script> in the HTML part, it doesn't execute it (and with the modified css would print it instead), but if you place it before, the code will execute.

Setting display CSS property of a <script> tag may result in its content being printed. That was the case for me.

Related

I Set Up a Javascript Function to Run Upon Button Click But Code Doesn't Execute

Alright, I will put this out there now, my knowledge of programming isn't super great. Only been programming for a few months.
I've been interested in making a browser based game and am currently just playing around with the code to see how things work.
I have both HTML and Javascript in my code. I am trying to get it so that when ButtonA is pressed, VariableA increases by set amount. I've done this before on other small programs I've done, so I simply did exactly what I did on the other programs, but for some reason, when the button is clicked, the variable is not changed.
My button is defined in the HTML code, and the function is run from the javascript. I'll put the code here so you can see for yourselves.
<script type="text/javascript">
//DEFINED VARIABLES
var playerLevel = 1;
var playerExp = 0;
var playerGold = 0;
var playerCredits = 0;
var neededExp = 30;
//FIGHT BUTTON
function Fight() {
playerExp += 5;
document.getElementById("playerExp").innerHTML = playerExp;
}
</script>
That is all the Javascript code my program currently has. The function setup looks perfectly fine to me. Now here is the HTML code for the button setup.
<h3>
<button type="button" onClick="Fight"><background color="gray"><font color="black">Fight!</font></button>
</h3>
The button is the same way I have always done buttons and had them working. I have it put into the h3 tag because I placed the button on the page using my stylesheet. For which the code I have is:
h3 {
position: fixed;
top: 283px;
left: 20px;
}
I know I am probably missing something simple, but as far as I can tell everything looks to be setup exactly how my other games buttons have been setup. The issue that I can't figure out is when the button is pressed, the variable playerEXP does not increase, or, if it is increasing, it's not updating the variable display. I also had my friend who is in the same class as me look it over and he said it looked fine as well.
Been at it over an hour, any help is greatly appreciated.
call function in paranthesis
<h3>
<button type="button" onClick="Fight();"><background color="gray"><font color="black">Fight!</font></button>
</h3>

Button to toggle all divs of certain class (pure javascript, or loading after jquery)?

I'm trying to insert a toggle button into a wordpress page that will change the state of all divs of class "foo".
Is there either a pure javascript way to do this, or some way of guaranteeing the js will load after the jquery.js loads? I don't really want to deal with trying to figure out how wordpress loads javascript and enqueuing files in the proper order or whatever, this should be 3 lines of javascript that is only needed on this one page.
My HTML / javascript knowledge is minimal, so please include the full code needed.
More details:
There is jquery in my theme, however if I try to use the $(".CLASSNAME").toggle() syntax, I get
"Uncaught TypeError: undefined is not a function"
Which I assume is something to do with my "page" javascript being loaded before jquery is loaded.
I tried various things, like
CSS
.excerpt{
style="display: none"
}
HTML
<input type="submit" value="Show/Hide Excerpts" onclick="toggleDiv();"></input>
<div class="excerpt">text i want to toggle</div>
Javascript, inside "script" HTML tag
$(document).ready(function toggleDiv() {
$(".excerpt").toggle();
} )
This results in the aforementioned "Uncaught TypeError: undefined is not a function"
This looks promising, but I'm not quite sure how to tweak it to toggle / be linked to a button:
https://stackoverflow.com/a/5836870/851192
For the gory details,
This is Wordpress 4.0.1, TwentyFourteen Theme, on a page created with the W4 Post List plugin.
I've been at this for three hours :/ Sigh.
This should work for you (I modified this a bit: https://stackoverflow.com/a/5836870/851192):
Javascript:
function toggleDiv() {
var divs = document.getElementsByTagName('div');
var toggle = function() {
for (var i = 0, l = divs.length; i < l; i++) {
if (divs[i].getAttribute('class') == 'excerpt')
if (divs[i].style.display == 'none') divs[i].style.display = '';
else divs[i].style.display = 'none';
}
}
}
HTML:
<input type="submit" value="Show/Hide Excerpts" onclick="toggleDiv();"></input>
...
<div class="excerpt">...</div>
Note that you do not need the class excerpt defined in CSS at all.
All the Javascript code needs is that all the divs you want toggled are marked with this class:
if (divs[i].getAttribute('class') == 'excerpt')
If the div is of class excerpt, then this toggles the display style:
if (divs[i].style.display == 'none') divs[i].style.display = '';
else divs[i].style.display = 'none';
Probably, it is due to WordPress loads in "no conflict" mode.
http://codex.wordpress.org/Function_Reference/wp_enqueue_script#jQuery_noConflict_wrappers
jQuery noConflict wrappers
Note: The jQuery library included with WordPress loads in "no conflict" mode. This is to prevent compatibility problems with other javascript libraries that WordPress can load.
In "no-confict" mode, the $ shortcut is not available and the longer jQuery is used. For example:
$(document).ready(function(){
$(#somefunction) ...
});
Becomes:
jQuery(document).ready(function(){
jQuery(#somefunction) ...
});
SOLUTION
Use jQuery instead of $.
function toggleDiv(){
jQuery('.excerpt').toggle();
}
Include your jQuery reference first then include your jQuery code in an IIFE (Immediately Invoke Function Expression) like this:
<script src='jquery/location'></script>
<script src='myscript/location'></script>
The IIFE should look like this:
(function($){
$('.excerpt').toggle();
})(jQuery)
Both of these script tags should be the last tags before your closing </body> tag. This way your content is loaded and the use does not have to wait for your scripts to load before he/she sees the content. If you need the elements hidden on load (i.e. you try it and the elements are visible when the page load and then are hidden) then you should apply a CSS style and use jQuery's toggleClass() method to hide/show or apply display:none; directly to the element and use toggle() when you want to show the item.
.hidden{
display:none;
}
The other problem you are going to have is your input type is submit which with trigger a POST (or GET). This does not look like what you want to do so you should use a button tag with the type=button.
Bind an click event in jQuery:
$('#toggle').on('click', function(){
$('.excerpt').toggleClass('hidden');
});
Here a Fiddle: http://jsfiddle.net/24xfa0sL/1/
I haven't dug through the responses yet, thanks for all of them. upvotes for everyone on the mythical day I get 15 points. Sorry for my not-perfectly-edited question, I was ready to go to sleep at that point.
I ended up figuring it out based on this jsfiddle:
http://jsfiddle.net/robert/PkHYf/
HTML
<button id="Toggle">Show/Hide Excerpts</button>
[...stuff...]
<div class="excerpt" style="display:none;">
<ul style="margin:0 0 5px 20px;">[excerpt wordlimit=20] </ul></div>
JS
var divs = document.getElementsByTagName('div');
var toggle = function() {
for (var i = 0, l = divs.length; i < l; i++) {
if (divs[i].getAttribute('class') == 'excerpt')
if (divs[i].style.display == 'none') divs[i].style.display = '';
else divs[i].style.display = 'none';
}
}
document.getElementById('Toggle').onclick = toggle;
picture of before/after button clicking to clarify desired behavior

HTML Button NOT Displaying Javascript Coded Image Display

I have some javascript functionality that did work at one time, a few weeks ago, but wasn't crucial while I developed an application for my company, so I didn't notice when it seemed to simply stop working...but now it matters. It's a button which, when clicked, should display an image below the button. At present nothing happens when I click the button...though it used to properly display the image.
Here is the original code (in the head of the page):
function getImageFL()
{
var x = document.getElementById("flacBtn").value;
document.getElementById("flac_place").src=x;
}
And the the button tag (from the body of the page):
<button id="flacBtn" value="other_pages/images/flac.png" onclick="getImageFL()">Click for image of FLAC model</button><br>
<img id="flac_place" height="200" width="349" style="visibility:hidden">
Today I tried something else, for another button/image pair, but this doesn't seem to do anything either...the new code (also in head):
function getImageRW()
{
var x = document.getElementById("rwBtn").value;
var image = document.getElementById('rw_place');
image.setAttribute('src', x);
image.style.visibility='visible';
}
And in the button tag (in body):
<button id="rwBtn" value="other_pages/images/3D-3.png" onclick="getImageRW()">Click for image of RW model</button><br>
<img id="rw_place" height="170" width="425" style="visibility:hidden">
Any ideas why neither of these do a thing? And why the first one, at least, used to? Thanks!
The first one wouldn't work as you forgot to set visibility='visible'; on there
function getImageFL()
{
var x = document.getElementById("flacBtn").value;
document.getElementById("flac_place").src=x;
document.getElementById("flac_place").style.visibility = 'visible';
}
Fiddle here
The 2nd one works for me: http://jsfiddle.net/tTLf6/

change the position of div tag dyanmically with javascript

I have an ASP button in a div to the right side of a page. I want to change the position to the left in the same row dynamically with onchange event of a dropdown.
I did this way:
document.getElementById('divButtonGo').style.Paddingleft="80px"
How do I do this with Javascript?
The example you have provided already is javascript. If you want to change what triggers the code to run, change where you place it.
from an onchange event, into a function in a script tag that is called by something else.
example
<input type="button" onclick="movediv()" />
<script>
function movediv(){
document.getElementById('divButtonGo').style.Paddingleft="80px"
}
</script>
There's several things wrong here. In order of increasing importance:
You're missing the closing slash from your i tag.
I don't see a "divButtonGo" in your html. If it's not there at all, obviously it won't work. If it is, include it in your code snippet.
I'm pretty sure to set the style you're going to need elem.style.paddingLeft, not elem.style.Paddingleft
Your script isn't wrapped inside <script> tags. All Javascript has to be wrapped in these tags, and, in order for that code to operate sucessfully, it's going to have to be placed after the "divButtonGo", or you'll have to wire up an onload event, like window.onload = function() { /* Bombs away! */ };
Your final result should look something like...
<div id="divButtonGo">
My Awesome Content
</div>
<script type="text/javascript">
var el = document.getElementById("divButtonGo");
el.style.paddingLeft = "30px";
</script>
Also, to note, padding wont' exactly change the position of the div, only the position of the content inside. If you want to change the position of the div, use margin-left (in JS, element.style.marginLeft, i believe)
EDIT:
I forgot you wanted it in the onchange event of a dropdown; so you'd do somethign like:
var dropdown = document.getElementById("MyDropDown");
dropdown.onchange = function() {
var el = document.getElementById("divButtonGo");
el.style.paddingLeft = "30px";
};

DIV with an onclick function and an image inside of it has a dead spot

I have a DIV with in image inside of it. There is a spot right before the image that does not fire the onclick function when clicked. The rest, including the image and the DIV fire the function when clicked. I have tried attaching the function to the image itself in addition to the DIV and this does not fix the problem. Anyone know what to do?
//this give all the divs the function
var ButtonNumber = document.querySelectorAll(".ButtonStyle");
for (var i = 0; i < ButtonNumber.length; i++) {
ButtonNumber[i].onmouseover = ChangeCursor;
ButtonNumber[i].onclick = ButtonsAddTogether;
ButtonNumber[i].onselectstart = function() {return false;}
}
This is the HTML
<div id="55" class="ButtonStyle"><img alt="1" class="Center" src="Buttons/7.png"></div>
Try setting the image and the div to have the same height. That or use an inline element rather than a block element such as an anchor tag
I have placed your code within jsfiddle: http://jsfiddle.net/BUwFP/1/
Please look at it and tell me if it works for you. I have just:
defined functions that were not defined (probably you just skipped them showing your code),
added borders to image and the div that contains it,
and everything looks fine - clicking the box etc. fires events. Do similar thing and check whether your box really is placed where you click or somehow it has been moved (probably by CSS styles or JS code). You probably already know, that you may use Firebug in Firefox, Developer Tools in Chrome or anything similar.

Categories