Works locally but not online - javascript

I have it so when you click on the elements such as the top right one hydrogen it plays a video in the big center div and displays info about hydrogen. I got it to work locally but i am unable to get it to work online.
Please any help would be great.
Here is the link to my project
http://travismichael.net/periodic_elements/
Here is the script for my site
<script type="text/javascript">
$(document).ready(function() {
$('div.video').hide();
$('.icon').click(function(){
var id=$(this).data('id'),
thisDiv=$("div.video[data-id='" + id +"']"),
thisVideo=$("div.video[data-id='" + id +"']").find('video');
$('video').each(function() {
this.pause();
this.currentTime = 0;
});
$('div.video').not(thisDiv).fadeOut('fast');
thisDiv.fadeIn();
thisVideo.get(0).play();
});
});
</script>
<script type="text/javascript">
$("#periodictable td").hover(function() {
$(this).stop().animate({opacity: "1"}, 'fast');
},
function() {
$(this).stop().animate({opacity: ".7"}, 'slow');
});
</script>

Error is here:
You're trying with
var thisDiv = ("div.video[data-id='" + id +"']");// but it returns jQuery object,
// not element
// Thats why below statement will not work
// because it works on element
alert(thisDiv.nodeType);
So you should try like this:
var thisDiv = ("div.video[data-id='" + id +"']")[0]; // returns the element
alert(thisDiv.nodeType); // and then get the nodeType

When checked I get an error message that says the Element is undefined.
you should past the error your console is giving you, as it is going to give much more explanation to what you are looking for.
It is obviously throwing an exception and whatever your exception is is displaying the error message, so...you try it on your local host where the files are defined. Are they declared in your code with a pointer or something to say go look back here and use this when the button is clicked?
It looks like your function should contain these declarations, or you could make them global, not really sure without more info...

Related

DOM change - no effect. Effect visible only if changed with timeout

Weird problem. I'm modifying shop template:
https://demo.themeisle.com/shop-isle/product-category/clothing/dresses/
At this moment when you hover product's picture there will show "add to cart" button. This is .
Under picture there is price
I prepared code:
var from = document.getElementsByClassName("woocommerce-Price-amount amount");
jQuery(document).ready(function(){
jQuery.each(from, function(i, el) {
jQuery(el.parentNode.parentNode).find(jQuery(".product-button-wrap")).append(el);
});
});
Nothing happens. This code work only if I set timeout:
setTimeout(function() {
var from = document.getElementsByClassName("woocommerce-Price-amount amount");
jQuery(document).ready(function(){
jQuery.each(from, function(i, el) {
jQuery(el.parentNode.parentNode).find(jQuery(".product-button-wrap")).append(el);
});
});
}, 10000);
Of course timeout it's not a solution. I was trying to find out minimal time to obtain best behavior but it's impossible. I have feeling that every browser (and version...) needs personalized time setting.
I thought that after 24-hour break I will get some brillant idea, but that doesn't work, no more ideas.
--- EDIT ---
OK, thanks for pointed mixed common js with jquery - I will correct that later.
jQuery(document).ready(function(){
var from = document.getElementsByClassName("woocommerce-Price-amount amount");
jQuery.each(from, function(i, el) {
jQuery(el.parentNode.parentNode).find(jQuery(".product-button-wrap")).append(el);
console.log(el);
});
});
That's logical that var from should be inside ready but this still doesn't work. No effect.
If I use in loop console.log it will return for me html code of el.
--- EDIT ---
Thanks. While testing I noticed something. I wanted append element .woocommerce-Price-amount.amount to element .product-button-wrap. But how can I do that if element .product-button-wrap isn't originally in source? This object is created dynamically (I don't know how).
-- EDIT --
OK. I checked JS files and found code adding to DOM .product-button-wrap so I putted my code there and now everything works. Thanks for help.
The problem is because you're running your code before the DOM has loaded. You need to retrieve the elements within the document.ready event handler.
Also note that you have an odd mix of native JS and jQuery methods. I'd suggest using one or the other, like this:
jQuery(function($) {
$('.woocommerce-Price-amount.amount').each(function() {
$(this).parent().parent().find('.product-button-wrap').append(this);
});
});
Also note that .parent().parent() should be replace by a single call to closest(), but I can't give you an exact example of that without seeing your HTML.

How to guarantee that a script in the middle of the body runs after all the DOM has finished load

In my <body> I have a component that inserts a script that is supposed to run only after all the page has completely loaded:
<script>
$('<script id="smallPlacarScriptdId">\
$(window).load(function() {\
$(".main.right").hide();\
$("#rightzero").show();\
$(".comp.smallPlacard.firstChild").click(function () {\
var clicked = $(this).parent().attr("id");\
$("main.right").hide();\
$("#right"+clicked+"").show();\
});\
})\
<\script>').appendTo("body")
</script>
That's not happening and this script (1) is correctly inserted into the DOM but (2) is not working (not hiding .main.right nor showing #rightzero).
I though that by using this approach I would guarantee that it would be the same as just put this script at the bottom of the <body> but it isn't. In fact if I put it (not dynamically like this) in my page it produces the desired result.
I tried setTimeout() to validate my theory but I'm getting an error in jQuery and I'm lost.
That might be the problem:
<\script>').appendTo("body")
Browser might think you are actually closing your script tag. Change it to
</' + 'script>').appendTo("body")
Check this plunker out: http://plnkr.co/edit/Oc6yrFMdPoW2WV257CBQ?p=preview
Just use this code
<script id="smallPlacarScriptdId">
$(window).load(function() {
$("main.right").hide();
$("#rightzero").show();
$(".comp.smallPlacard.firstChild").click(function () {
var clicked = $(this).parent().attr("id");
$("main.right").hide();
$("#right"+clicked+"").show();
});
})
</script>
Sorry I didn't read you question well enough.
Javascript will allow you to access undeclared variables, so use that to your advantage. Check if a variable is set, undefined is treated as a false so no need for initialization. As soon as you enter the code just set it to true so nothing else will execute.
Hopefully this solves the problem for you, but you really should look at from the server avoiding the javascript, it will bloat the page.
<script>
if (!myScriptHasLoaded)
{
myScriptHasLoaded = true;
$(window).load(function() {
$("main.right").hide();
$("#rightzero").show();
$(".comp.smallPlacard.firstChild").click(function () {
var clicked = $(this).parent().attr("id");
$("main.right").hide();
$("#right"+clicked+"").show();
});
});
}
</script>

Console.log not working at all

A bunch of code isn't working and I'm trying to identify where the problem lies but console.log() isn't logging any results in Chrome Dev tools, am I doing it correctly?
$(window).scroll(function() {
$('section').each(function(){
var id='#'+$(this).attr('id'),
off=$(id).offset().top,
hei=$(id).height(),
winscroll=$(window).scrollTop(),
dif=hei+off-($(window).height());
if (winscroll >= off && winscroll<=dif) {
console.log('first broken');
$(id+' .sticky').removeClass('abs').addClass('fix');
} else if (winscroll > dif){
console.log('second broken');
$(id+' .sticky').removeClass('fix').addClass('abs');
} else {
console.log('third broken');
$(id+' .sticky').removeClass('fix abs');
} });
});
EDIT FULL CODE ADDED
$(document).ready(function() {
// If a browser supports 3D transforms use the fancy menu if it doesn't, use standard accordion menu instead
if($('html').hasClass('csstransforms3d')){
$( "#mp-menu" ).removeClass( "snap-drawers" ).addClass( "mp-menu" );
$('nav ul li ul').css('border-bottom','1px solid rgba(255, 255, 255, .05)');
$('nav ul li ul').css('background','none');
// Insert elements where necessary to create the right structure
$('#mp-menu').wrapInner('<div class="mp-level" />');
$('#mp-menu').find('li > ul').wrap('<div class="mp-level" />');
$("#mp-menu ul li .mp-level").prepend(function () {
return '<span class="menu-title">' + $(this).prev().text() + '</span> <a class="ico mp-back" href="#">Back</a>';
});
// load in necessary JS files
$.getScript('http://176.32.230.2/baodev.com/cjo/wp-content/themes/CJO/js/multi-level-menu.js');
} else {
// load in necessary JS files
$.getScript( "http://176.32.230.2/baodev.com/cjo/wp-content/themes/CJO/js/jquery.navgoco.min.js", function() {
$("#demo1").navgoco({accordion: true});
});
$.getScript( "http://176.32.230.2/baodev.com/cjo/wp-content/themes/CJO/js/snap.min.js", function() {
// Snapper settings
var snapper = new Snap({
element: document.getElementById('scroller'),
disable: 'right',
maxPosition: 291
});
var addEvent = function addEvent(element, eventName, func) {
if (element.addEventListener) {
return element.addEventListener(eventName, func, false);
} else if (element.attachEvent) {
return element.attachEvent("on" + eventName, func);
}
};
// Toggle button
addEvent(document.getElementById('trigger'), 'click', function(){
if( snapper.state().state=="left" ){
snapper.close();
$( ".menu-trigger" ).removeClass( "active" );
} else {
snapper.open('left');
$( ".menu-trigger" ).addClass( "active" );
}
});
addEvent(document.getElementById('scroller'), 'click', function(){
if( snapper.state().state=="left" ){
$( ".menu-trigger" ).removeClass( "active" );
}
});
/* Prevent Safari opening links when viewing as a Mobile App */
(function (a, b, c) {
if(c in b && b[c]) {
var d, e = a.location,
f = /^(a|html)$/i;
a.addEventListener("click", function (a) {
d = a.target;
while(!f.test(d.nodeName)) d = d.parentNode;
"href" in d && (d.href.indexOf("http") || ~d.href.indexOf(e.host)) && (a.preventDefault(), e.href = d.href)
}, !1)
}
})(document, window.navigator, "standalone");
});
} // end if
fitHeight();
$(window).scroll(function() {
$('section').each(function(){
var id='#'+$(this).attr('id'),
off=$(id).offset().top,
hei=$(id).height(),
winscroll=$(window).scrollTop(),
dif=hei+off-($(window).height());
console.log('msj');
if (winscroll >= off && winscroll<=dif) {
$(id+' .sticky').removeClass('abs').addClass('fix');
} else if (winscroll > dif){
$(id+' .sticky').removeClass('fix').addClass('abs');
} else {
$(id+' .sticky').removeClass('fix abs');
}
});
});
});
// Trigger FitHeight on browser resize
$(window).resize(fitHeight);
EDIT
Some bits of the full code (above) refer to other JS files and code returns no errors when run with these files present. After troubleshooting I see the console message before the scroll function but I do not see the console message within the scroll function.
fitHeight();
console.log('About to bind scroll effects'); // I SEE THIS MESSAGE
$(window).scroll(function() {
console.log("scroll bound, now loop through sections"); //BUT NOT THIS ONE
$('section').each(function(){
In my case, all console messages were not showing because I had left a string in the "filter" textbox.
Remove the filter it by clicking the X as shown:
Sounds like you've either hidden JavaScript logs or specified that you only want to see Errors or Warnings. Open Chrome's Developer Tools and go to the Console tab. At the bottom you want to ensure that JavaScript is ticked and also ensure that you have "All", "Logs" or "Debug" selected.
In the image above I have JavaScript, Network, Logging, CSS and Other ticked and "All" selected.
Another potential problem could be that your $(window).scroll() function isn't wrapped within a .ready() function (as documented here):
$(document).ready(function() {
$(window).scroll(function() {
...
});
});
When pasting your code into JSFiddle and giving some dummy content, your code works perfectly fine: JSFiddle demo.
Edit:
The question was edited. The new code given throws two errors:
Uncaught ReferenceError: fitHeight is not defined
Uncaught TypeError: Cannot read property 'addEventListener' of null
Because of this, the code stops execution prior to reaching any console.log call.
Click on the restore button. console.log will start to work.
I feel a bit stupid on this but let this be a lesson to everyone...Make sure you target the right selector!
Basically the console wasn't logging anything because this particular code snippet was attempting to grab the scrolling area of my window, when in fact my code was setup differently to scroll an entire DIV instead. As soon as I changed:
$(window).scroll(function() {
to this:
$('#scroller').scroll(function() {
The console started logging the correct messages.
It was because I had turned off "Logs" in the list of boxes earlier.
2021 solution
open developer tools
navigate to "console"
most likely "Verbose" is not ticked, so activate it
In my case I was developing a Polymer WebComponent, which is included using <link rel="import"> into the main HTML document. Turns out that the WebComponent HTML file was being cached for some reason, even though I had changed it since the cached version.
To solve it I opened the Developer Console (in Chrome), right clicked on the reload arrow next to the URL bar and selected "Empty cache and hard reload" - problem solved.
Somewhere console.log had been overridden in a js file somewhere (that I haven't been able to locate).
But I could test by putting console.log in the console and I only got an empty function: f{}
I added this to the top of my own js file to correct it (absolute hack, but worked for me):
var console = window.console;
Just you need to select right option to show the log messages from the option provided in left side under the console tab. You can refer the screen shot.
I just had a same issue of none of my console message showing. It was simply because I was using the new Edge (Chromium based) browser on Windows 10. It does not show my console messages whereas Chrome does. I guessed it was an issue with Edge because I had another odd issue with Edge because it treated strings with single quotes and double quotes differently.
Consider a more pragmatic approach to the question of "doing it correctly".
console.log("about to bind scroll fx");
$(window).scroll(function() {
console.log("scroll bound, loop through div's");
$('div').each(function(){
If both of those logs output correctly, then its likely the problem exists in your var declaration. To debug that, consider breaking it out into several lines:
var id='#'+$(this).attr('id');
console.log(id);
var off=$(id).offset().top;
var hei=$(id).height();
var winscroll=$(window).scrollTop();
var dif=hei+off-($(window).height());
By doing this, at least during debugging, you may find that the var id is undefined, causing errors throughout the rest of the code. Is it possible some of your div tags do not have id's?
As a complete new at javascript, I just had the same problem on my side here. The mistake I did, was that I used:
<script type="text.javascript">
console.log("bla bla bla");
</script>
instead of:
<script>
console.log("bla bla bla");
</script>
using the
type="text.javascript"
had the result of not producing the log in the console.
In my case it was caused by console.groupCollapsed().
And collapsed messages don't get detected by ctrl+f apparently.
Maintaining unfamiliar code is scary sometimes...
It even collapsed the exception message, absence of which made me put those console.logs in the first place ^_^
if using $ parameter in console.log within html, then single quotes(') and double quotes("") will not work.
use quotes like (` `)
example:
console.log(`${address}`);
This will help when using the $ parameter and anyone facing issues in console.log.

Removing Yet not Deleting an Element/Variable from an HTML Document

I am testing out with a different way of menus. My code is the following:
JavaScript
var hubOpen = 0;
var test = "test";
$(document).ready(function(){
$('#hub').click(function(){
if(hubOpen == 0){
$('#hub').append(test);
hubOpen = 1;
} else {
//code for taking "test" out here
hubOpen = 0;
};
});
});
HTML
<body>
<p id="hub">Hub</p>
</body>
If you'd like, here's a jsFiddle here. The code is to make sure that when the id "hub" is clicked, "test" appears. When hub is clicked again, "test" disappears. The code, when run, opens test, doesn't let you click it again, but it doesn't delete "test" (as there is no code for it).
My question: How would I delete the variable "test" from the document but not to delete the variable forever, as I would need to use it later? Would the jQuery method
.replace();
work?
Thanks in advance!
To remove all the contents of an element, jQuery offers .empty():
$('#hub').empty();
The variable is completely separate from the element, so no problems there. If you wanted to restore the original text, just use .text():
$('#hub').text('Hub');
Updated fiddle
You can do something like this:
$(document).ready(function(){
$('#hub').click(function(){
$(this).text() == 'Hub' ? $(this).html('text') : $(this).html('Hub');
});
});
On click if the text is 'Hub' change it to 'text' else change it again to 'Hub'.

Unable to find click event

Here is my JQuery Code:
$(function () {
$('[id*=clickbtn]').click(function () {
var url = "WindowPages/EditorControl.aspx?controlName=" + this.name;
oWnd.setUrl(url);
oWnd.show();
});
});
Now the problem is, i have 4 to 5 buttons whose id contains 'clickbtn' when i click the any one of them for first time it works well. But it does not works for second click, any help why is this happening?
[EDIT]:
I tried putting the JQuery on page and it worked.. But wnt to know why it does not work on when i put the same on .JS file?
Yes, the result of your event handlers depends very much on the content of your event handlers. If you'd like to share with us the rest of the code we might be able to help. For now the answer is: working as intended
jsFiddle
If your clicks only work on the first try, then I can assure you that it is only the missing code which is to blame. Provide the contents of oWnd.setUrl and oWnd.show and we might be able to help.
Your wildcard selector is wrong. It should be
$("[id$=clickbtn]")
Try this:
$('input[ID*="Button"]')
OR
First set class="btn" to all buttons you want to do this action then
$(function() {
$('.btn').click(function() {
var url = "WindowPages/EditorControl.aspx?controlName=" + this.name;
oWnd.setUrl(url);
oWnd.show();
});
});

Categories

Resources