Below is my snippet of code, intended to show the comments of a certain thread that's selected.
$('.comments-count').click(function(){
if(!commentsDown){
$(this).parent().parent().siblings('.comments').stop().slideDown();
commentsDown = true;
currentlyDown = $(this).parent().parent().siblings('.comments');
}else{
$(currentlyDown).stop().slideUp();
var newDown = $(this).parent().parent().siblings('.comments');
if(newDown != currentlyDown){
$(this).parent().parent().siblings('.comments').stop().slideDown();
commentsDown = true;
currentlyDown = $(this).parent().parent().siblings('.comments');
}else{
commentsDown = false;
currentlyDown = null;
}
}
})
The line $(currentlyDown).stop().slideUp(); works if you post it into the console, but for some reason it's ignored in this script. I put in console.log() commands and it showed that it definitely should execute it.
commentsDown and currentlyDown are global variables, initially set to false and null respectively.
Here's a JSFiddle. The threads are currently static HTML. As you can see, if you open a thread and then open a different one it works fine, but it doesn't work to close a thread.
You should be able to reduce your whole block of code to:
$(document).ready(function () {
$('.comments-count').click(function () {
$('.comments-count').not($(this)).parent().parent().siblings('.comments').stop().slideUp();
$(this).parent().parent().siblings('.comments').stop().slideToggle();
})
//Log colour pattern
$('div.event-log-entry:even').addClass('evens');
$('div.event-log-entry:even .comments-count').addClass('evens');
})
jsFiddle example
Add your function inside document.ready tags;
$(document).ready(function () {
//insert your code here
});
For more info. go on this site:
http://learn.jquery.com/using-jquery-core/document-ready/
Hope it helps :)
Related
I have the following JS on my html and my obervations are:
1) When I removed the line for "alert" display it is not working as expected, the SAVE button is not trigerring when clicked.
2) Even with the "alert", it is not working in CHROME.
function save() {
alert('View Full List triggered!');
var $form = $('.fancybox-inner').find('[data-area="funder-detail"]');
$form.on('click', '[data-action="save-funder"]', function () {
var selected1 = $form.find('input[type="radio"]:checked').val();
if ($('input[type="radio"]:checked').length == 0) {
parent.$.fancybox.close();
} else {
document.getElementById("txtFunder").value = selected1;
parent.$.fancybox.close();
}
});
}
Perhaps the script runs too early, when the form is not yet in the DOM?
This can happen when the script tag is in the header.
Try moving the script tag in front of the closing tag.
I was able to make it work by using onclick="setTimeout(save, 1000)"
there is a page with some basic HTML that I cannot touch that looks like this:
<a class="continue-shopping" href="https://someURL">Continue shopping</a>
what I want to do is send the user to a different link when they click on the someURL text link. the user can come to a page containing this html from many other pages.
i have tried many hours but cannot get my js to recognize a click event for a class associated with hyperlinked text. i could really use some help here. this is the js code i wrote which does not work
window.onload = function() {
prepEventHandler();
}
function prepEventHandler () {
var myClass = document.getElementsByClassName("continue-shopping");
myClass[0].onclick=window.open(document.referrer,"_self");
/* which make my pages go haywire OR THIS -- which also does not work */
myClass[0].addEventListener("click", function() {
window.open(document.referrer,"_self");
}
)
}
It just keeps ignoring the second function, and I am sure I am doing some really basic that is wrong. Again, thanks for any help!
Apart from preventDefault() you could also use return false
window.onload = function () {
var myClass = document.querySelector(".continue-shopping")
.onclick = function () {
window.location.href = "http://elsewere.com";
return false;
}
}
this code should work but it no longer does and i do not know why any hint much appreciated - there seems to be some problem with myClass[0]
window.onload = function() {
var myClass = document.getElementsByClassName('continue-shopping');
myClass[0].addEventListener("click", function(e) {
e.preventDefault();
window.location.href = document.referrer;
});
}
Java script in Html is as follows.
$(document).ready(function () {
var found = {{.found}}
window.alert("hiiii");
if (foundRecords==true) {
document.getElementById("abc").style.display = "block";
}
return
});
This should get loaded during the time of html loading. But it's not at all loading. I didn't find anything wrong in this simple peace of code.
if you want to get elements with class found {{.found}}
window.onload = function()
{
var found = document.getElementsByClassName("found");
if (found) {
document.getElementById("abc").style.display = "block";
}
}
If you use jQuery to load that function it will take a slight change:
$(document).ready(function () {
// get the class found and assign it to a variable found
var found = $('.found') // it was {{.found}} producing an error
window.alert("hiiii");
// where does foundRecords come from? it is up to you to clear this
if ( foundRecords == true ) {
document.getElementById("abc").style.display = "block";
}
// what is the return good for?
// it would be better to return true or false
// or leave it away
return;
});
Check the jsFiddle:
http://jsfiddle.net/bx0e18L4/
Now it alerts the message, but still has the problem with the variable foundRecords. Take care for that.
EDIT:
According to your comments above the variable foundRecords should be found, so the critical line should be:
if ( found == true ) { // processing }
I know this has been asked multiple times, but neither of the answers seem to help me.
I've been almost two days trying to get around this but I haven't been able to figure out what's going on.
I have the following code:
alert('Before document.ready');
$(document).ready(function () {
alert('Actual document.ready');
addNumberValidation($("#quantity"), $("#quantityError"));
addNumberValidation($("#price"), $("#priceError"));
$("#form").submit(function(){
var quantityValid = validar( $("#quantity"), $("#quantityError") );
var priceValid= validar( $("#price"), $("#priceError"));
var formValid = quantityValid && priceValid;
return formValid ;
});
});
function addNumberValidation(mainElement, errorElement) {
mainElement.keyup(function () {
validate($(this), errorElement);
});
}
function validate( mainElement, errorElement) {
var regex = /^[0-9]+$/;
var result = false;
if ( mainElement.val().match(regex)) {
errorElement.text('');
result = true;
} else {
errorElement.text('Must be a number');
result = true;
}
return result;
}
The script is getting loaded correctly because the "Before document.ready" alert is getting called correctly. Also, jQuery is getting loaded as well because other js code is executing properly.
My console shows no error whatsoever and the script under the sources tab in Chrome is complete.
I documented the functions to see if there was something wrong with that and it still didn't work.
Any insights of what could be going on?
Found the issue. Another library was making a conflict that avoided the document.ready to get called
First Question here, too! Yay! Just moved this from AskUbuntu.
I am just about to finish a little private project for gaining some experience where i try to change the app layout so it works as a normal website (on Jimdo, so it was quite of a challenge first) without much JavaScript required but is fully functional on mobile view.
Since Jimdo serves naturally only the actual site, I had to implement an
if (activeTab.getAttribute('jimdo-target') != null)
location.href = activeTab.getAttribute('jimdo-target');
redirect into the __doSelectTab() function in tabs.js . (In js I took the values from the jimdo menu string to build the TABS menu with this link attribute)
Now everything works fine exept at page load the first tab is selected. I got it to set the .active and .inactive classes right easily, but it is not shifted to the left.
So my next idea is to let it initialize as always and then send a command to change to the current tab.
Do you have any idea how to manage this? I couldn't because of the this.thisandthat element I apparently don't really understand...
Most of you answering have the toolkit and the whole code, but I am listing the select function part of the tabs.js:
__doSelectTab: function(tabElement, forcedSelection) {
if ( ! tabElement)
return;
if (tabElement.getAttribute("data-role") !== 'tabitem')
return;
if (forcedSelection ||
(Array.prototype.slice.call(tabElement.classList)).indexOf('inactive') > -1) {
window.clearTimeout(t2);
activeTab = this._tabs.querySelector('[data-role="tabitem"].active');
offsetX = this.offsetLeft;
this._tabs.style['-webkit-transition-duration'] = '.3s';
this._tabs.style.webkitTransform = 'translate3d(-' + offsetX + 'px,0,0)';
this.__updateActiveTab(tabElement, activeTab);
if (activeTab.getAttribute('jimdo-target') != null)
location.href = activeTab.getAttribute('jimdo-target');
[].forEach.call(this._tabs.querySelectorAll('[data-role="tabitem"]:not(.active)'), function (e) {
e.classList.remove('inactive');
});
var targetPageId = tabElement.getAttribute('data-page');
this.activate(targetPageId);
this.__dispatchTabChangedEvent(targetPageId);
} else {
[].forEach.call(this._tabs.querySelectorAll('[data-role="tabitem"]:not(.active)'), function (el) {
el.classList.toggle('inactive');
});
var self = this;
t2 = window.setTimeout(function () {
var nonActiveTabs = self._tabs.querySelectorAll('[data-role="tabitem"]:not(.active)');
[].forEach.call(nonActiveTabs, function (el) {
el.classList.toggle('inactive');
});
}, 3000);
}
},
...and my app.js hasn't anything special:
var UI = new UbuntuUI();
document.addEventListener('deviceready', function() { console.log('device ready') }, true);
$(document).ready(function () {
recreate_jimdo_nav();
UI.init();
});
So meanwhile found a simple workaround, however I'd still like to know if there is another way. Eventually I noticed the __doSelectTab() function is the one that executes the click, so it does nothing but to show the other tab names when they are hidden first. so I added the global value
var jnavinitialized = false;
at the beginning of the tabs.js and run
var t = this;
setTimeout(function(){t.__doSelectTab(t._tabs.querySelector('[data-role="tabitem"].jnav-current'))}, 0);
setTimeout(function(){t.__doSelectTab(t._tabs.querySelector('[data-role="tabitem"].jnav-current'))}, 1);
setTimeout(function(){jnavinitialized = true;}, 10);
at the top of the __setupInitialTabVisibility() function. Then I changed the location.href command to
if (activeTab.getAttribute('jimdo-target') != null && jnavinitialized)
location.href = activeTab.getAttribute('jimdo-target');
And it works. But originally I searched for a way to change the tab on command, not to run the command for selecting twice. So if you know a better or cleaner way, you are welcome!