I'm trying to create a fairly simple script which uses links to toggle which div is being displayed. There is a div for each day, and when a corresponding link is clicked, it shows the according div and hides the others.
This works, but once you release the mouse it reverts back to the default state. I'm guessing this is something very simple, but I've tried searching around and can't find anything.
Here is the code I'm using:
Fiddle
$(document).ready(function() {
var dayDivs = [];
var displayDay = 0;
loadDayDivs();
adjustDayDisplay();
$('.day-link').mousedown(function() {
var linkClicked = $(this).text();
switch (linkClicked) {
case "Friday":
displayDay = 0;
break;
case "Saturday":
displayDay = 1;
break;
case "Sunday":
displayDay = 2;
break;
}
adjustDayDisplay();
});
function loadDayDivs() {
dayDivs[0] = $(".friday-div");
dayDivs[1] = $(".saturday-div");
dayDivs[2] = $(".sunday-div");
}
function adjustDayDisplay() {
for (var i = 0; i < dayDivs.length; i++) {
dayDivs[i].css("cssText", "display: none !important;");
}
dayDivs[displayDay].css("cssText", "display: inline !important;");
}
});
on jsfiddle I get a strange error which seems to be associated with forms normally. Any help on this would be VERY much appreciated.
You should change the mouse down event to click event and suppress the click event.
This fiddle works
$('.day-link').click(function(e) {
e.preventDefault(); // New line
You need to use click event and prevent default behavior using event.preventDefault(), otherwise the browser will actually open the link. Here is an updated fiddle - https://jsfiddle.net/yLrhrumx/2/
Related
Im trying to figure out how to in wordpress display only first two comments and hide rest and add button that reveal all these hidden messages if needed. Pagination give me only two msg per page and thats not im looking for. Can someone give me an idea how I can this achieve or point me to articles about this?
Thanks
here is a plugin that should do the job: https://wordpress.org/plugins/comment-load-more/
It is a bit outdated (3 years ago) so you should check if the code is still valid and compatible.
In " Settings > Comment Load" you should be able to set the number of desired comments to show first.
Indeed, in this guide - http://www.wpbeginner.com/plugins/how-to-easily-lazy-load-comments-in-wordpress/ - you will find how to lazy load all comments. Probably, with some modification, you can adapt it to your need as well.
Cheers!
// This function hide comments if is there more than two and add show more button
function fds_comments () {
var commentWrap = document.getElementById('comment-list');
var commentChilderns = commentWrap.children;
for (var i = 2; i < commentChilderns.length; i++) {
commentChilderns[i].style.display = "none";
}
commentWrap.innerHTML = commentWrap.innerHTML + "<button id='more-comments' onclick='fds_all_comments()'type='button' >Show all comments</button>";
}
//This function reveal all comments (used on SHOW MORE btn)
function fds_all_comments(){
var commentWrap = document.getElementById('comment-list');
var commentChilderns = commentWrap.children;
for (var i = 0; i < commentChilderns.length; i++) {
commentChilderns[i].style.display = "block";
}
}
// problem: comments hidden after submit
// solved: This additional code reveal comments after SUBMIT
window.onload = function() {
var reloading = sessionStorage.getItem("reloading");
if (reloading) {
sessionStorage.removeItem("reloading");
fds_all_comments();
}
}
// function used on SUBMIT button
function fds_all_on_submit(){
sessionStorage.setItem("reloading", "true");
document.location.reload();
}
I'm building a function in my own image browser that creates and displays a delete button when the user hovers the cursor over a certain image's div and hides the button when the user hover the mouse out of the div.
this is the code:
function displayImages() {
//run through array of images
for (a = 0; a < images.length; a++) {
var container = document.createElement('div');
container.id = 'container'+images[a];
container.style.width = 120;
container.style.backgroundColor = '#e9e9e9';
container.style.height = 140;
container.style.margin = 5;
container.style.display = 'inline-block';
container.style.float = 'left';
var imageID = images[a];
container.onmouseover = function() {imageRollover(this)};
container.onmouseout = function() {imageMouseOut(this)};
}
}
function imageRollover(image) {
var trashcan = document.createElement('BUTTON');
trashcan.id = 'trash'+image.id;
trashcan.className = 'deleteButton';
trashcan.onclick = function() {deleteImage(image.id);};
document.getElementById(image.id).appendChild(trashcan);
}
function imageMouseOut(image) {
document.getElementById(image.id).removeChild(document.getElementById('trash'+image.id));
}
function deleteImage(image) {
alert(image);
}
My problem is, that when I click trashcan, it calls nothing. I already tried to add the onlick event normally:
trashcan.onclick = deleteImage(image.id);
But then, for some reason, is calls the function when I hover my mouse over the container.
How do I make sure that on click events for dynamically added rollover buttons work?
The function can de viewed on: http://www.imaginedigital.nl/CMS/Editor/ImagePicker.html or http://jsfiddle.net/f239ymos/
Any help would be highly appreciated.
You are forcing me to guess here(not giving a fiddle), and create a scenario of my own but from what I understand, you want a button to appear no hover, and when pressed to delete the image so here its a working fiddle
hover functionality
$((document.body).on('mouseenter', '.test', function(){
console.log('here');
$(this).children('.test .x_butt').show();
});
$(document.body).on('mouseleave', '.test', function(){
$('.test .x_butt').hide();
});
remove functionality
$(document.body).on('click', '.x_butt', function(){
$(this).parent().remove();
});
P.S. as for your dynamically added divs issue, the $(selector1).on('click','selector2', function() {...}); deals with it, as long as selector1 is not added dynamically. (selector2 would be the div you want the function to be on) demo with dynamically added elements ( click clone )
First change
window.onload = loadImages(); to window.onload = loadImages;
Then since you pass an object you can change
function imageMouseOut(image) {
document.getElementById(image.id).removeChild(document.getElementById('trash'+image.id));
}
to
function imageMouseOut(image) {
image.removeChild(image.childNodes[0]);
}
However why not just hide and show the trashcan? Much cleaner
I am trying to build a menu which detects hover states and hide/shows relevant divs depending on where the mouse is. I need to do this with Prototype.js.
The menu looks something like this :
========ONE========TWO======THREE=======FOUR======FIVE======
============================================================
------------------- BIG MIDDLE DIV -------------------------
============================================================
============================================================
-------------------- TARGET HIDDEN DIV ---------------------
============================================================
When you mouse over link one,two,three.. it will show the related target div. The trick is when you mouseout, it needs to keep that div visible if you are on the middle div or the active state div. If you mouseout anywhere else in the body it needs to hide. Here is updated code based off the answer so far.
<ul><li #id="one">one</li><li>two</li><li>three</li><li>four</li></ul>
<div id="middleBar"></div>
<div id="container-one">1</div>
<div id="container-two">2</div>
<div id="container-three">3</div>
<div id="container-four">4</div>
<script>
MouseOff = true;
function getTarget(event) {
var el = event.target || event.srcElement;
return el.nodeType == 1? el : el.parentNode;
}
var ShowDiv = function(activeDiv){
$(activeDiv).addClassName('isActive');
var activeSibs = $(activeDiv).siblings();
activeSibs.invoke('removeClassName', 'isActive');
};
var HideDiv = function(){
if(MouseOff){
$$('div').invoke('removeClassName','isActive');
}
};
$$('li').invoke('observe','mouseenter',function(){
console.log(getTarget(event));
MouseOff = false;
var linkName = this.innerHTML;
var activeDiv = 'container-' + linkName;
ShowDiv(activeDiv);
});
$$('li').invoke('observe','mouseleave',function(){
MouseOff = true;
HideDiv();
});
$$('#middleBar').invoke('observe','mouseenter',function(){
console.log(getTarget(event));
MouseOff = false;
});
</script>
Here is a fiddle of this :
http://jsfiddle.net/TqMtK/5/
To further clarify what I am trying to achieve, once the div is activated it needs to stay visible while on that nav trigger, the middle bar, or the active div itself. Something else I was thinking was to use that getTarget function to always check what element the mouse is above, but this just feels wrong to me and does not seem very efficient. Any opinions on that?
UPDATE : Still trying to work through this.. now I am a little closer and the flag is set correctly when over middle div, but when it goes over the active div it resets the flag and the div disappears. I tried adding back a timeout.. here is latest attempt :
http://jsfiddle.net/TqMtK/7/
UPDATE : Ok I think I might have this, at this point I would like to just hear any feedback on this solution. I found that because the active class is being added dynamically the observer method must be included in the function that creates it : ShowDiv. Here is what I got :
http://jsfiddle.net/TqMtK/9/
UPDATED: tues night. I am sure this can be more succinct. Perhaps it is just my browser but I notice that I can only mouse over Panel1 and show that it doesn't disappear, the other Panels (because of their positioning) leave a space which is the "body" and I close on that. Hopefully this is a bit better.
http://jsfiddle.net/TqMtK/12/
var tabPanels = {
options : {
activePanel : "",
activeTab : ""
},
showPanel : function(panel){
this.hidePanel();
this.options.activePanel = 'container-' + panel;
this.options.activeTab = panel;
$(this.options.activePanel).addClassName('isActive').setAttribute('panel',panel);
},
hidePanel : function(panel){
if(Object.isElement($(panel)) && $(panel).hasAttribute('panel') ){
if($(panel).readAttribute('panel') == this.options.activeTab ){
return;
}else{
if(!this.options.activePanel.blank()){
$(this.options.activePanel).removeClassName('isActive');
}
}
}else{
if(!this.options.activePanel.blank()){
$(this.options.activePanel).removeClassName('isActive');
}
}
}
}
document.observe('mouseover', function(e){
switch(e.target.id){
case 'middleBar':
break;
case 'one':
case 'two':
case 'three':
case 'four':
tabPanels.showPanel(e.target.id);
break;
default:
tabPanels.hidePanel(e.target.id);
}
})
After much tinkering I finally found a working solution for this. Thanks to the idea from james I went the route of setting a flag depending on which element the mouse was over. That combined with a timeout allowed me to keep running checks on the mouse location. Part of my problem was where I was invoking the observe event on the class that was dynamically added from ShowDiv(), when I moved it in to that function I was able to get it to work. Here is the js I ended up with
MouseLocator = 'off';
var ShowDiv = function(activeDiv){
$(activeDiv).addClassName('isActive');
var activeSibs = $(activeDiv).siblings();
activeSibs.invoke('removeClassName', 'isActive');
$$('.isActive').invoke('observe','mouseenter',function(){
MouseLocator = 'on';
});
$$('.isActive').invoke('observe','mouseleave',function(){
MouseLocator = 'off';
setTimeout(function(){HideDiv()},500);
});
};
var HideDiv = function(){
if(MouseLocator == 'off'){
$$('div').invoke('removeClassName','isActive');
}
};
$$('li').invoke('observe','mouseenter',function(){
MouseLocator = 'on';
var linkName = this.innerHTML;
var activeDiv = 'container-' + linkName;
ShowDiv(activeDiv);
});
$$('li').invoke('observe','mouseleave',function(){
MouseLocator = 'off';
setTimeout(function(){HideDiv()},500);
});
$$('#middleBar').invoke('observe','mouseenter',function(){
MouseLocator = 'on';
});
$$('#middleBar').invoke('observe','mouseleave',function(){
MouseLocator = 'off';
setTimeout(function(){HideDiv()},500);
});
and a fiddle : http://jsfiddle.net/TqMtK/9/
I guess this is resolved but I am always open to suggestions on how to improve my code :)
I have a SUBMIT and SAVE button for a form that are by default listening for Onclick events.
When the form is SUBMITTED OR SAVED - the page resets the scroll position to the TOP of the page.
Recently the users of the applications have requested that the page stay at the bottom of the page where the buttons are located for only a subset of forms.
(These buttons are used across hundreds of other forms so I cannot change the reset of the scrolling globally.)
So the solution that I am trying to implement involves a couple hidden input fields and a few event listeners.
I have added an onmousedown event for these buttons, like so -
// Submit and Save button listeners
var globalButtons;
if (v_doc.getElementsByClassName) {
globalButtons = v_doc.getElementsByClassName('globalbuttons');
}
// Internet Explorer does not support getElementsByClassName - therefore implement our own version of it here
else {
globalButtons = [];
var myclass = new RegExp('\\b'+'globalbuttons'+'\\b');
var elem = v_doc.body.getElementsByTagName("input");
for (var i = 0; i < elem.length; i++) {
var classes = elem[i].className;
if (myclass.test(classes)) {
globalButtons.push(elem[i]);
}
}
}
for (var gb = 0; gb < globalButtons.length; gb++) {
if (globalButtons[gb].name == 'methodToCall.route' ||
globalButtons[gb].name == 'methodToCall.save') {
if(globalButtons[gb].addEventListener) { //all browsers except IE before version 9
globalButtons[gb].addEventListener("mousedown", function(){flagSpecialScrollOnRefresh()},false);
}
else {
if(globalButtons[gb].attachEvent) { //IE before version 9
globalButtons[gb].attachEvent("onmousedown",function(){flagSpecialScrollOnRefresh()});
}
}
}
else { continue; }
}
This code is located in a function called attachButtonListeners
Next, I defined my handler like so and placed it into another function that gets called each time my page is being loaded -
function checkSpecialScrollCase() {
var spfrm = getPortlet();
var sp_doc = spfrm.contentDocument ? spfrm.contentDocument: spfrm.contentWindow.document;
var specialScrollExists = sp_doc.getElementById(docTypeButton).value;
if (specialScrollExists == "YES") {
sp_doc.getElementById(docTypeButton).value = 'NO';
}
// else - nothing to do in this case
}
docTypeButton = REQS_BUTTONS
And it references the following element at the bottom of my JSP page -
<input type="hidden" id="REQS_BUTTONS" value="NO"/>
<a name="anchorREQS"></a>
Notice the anchor tag. Eventually, I need to add the location.hash call into my handler so that I scroll to this location. That part is irrelevant at this point and here is why.
Problem -
My flagSpecialScrollOnRefresh function is NOT setting the value to YES when it should be.
I believe my onClick event is happening too fast for my onmousedown event from happening.
Evidence -
If I place an alert statement like so -
function flagSpecialScrollOnRefresh() {
var scfrm = getPortlet();
var sc_doc = scfrm.contentDocument ? scfrm.contentDocument: scfrm.contentWindow.document;
alert("BLAH!");
sc_doc.getElementById(docTypeButton).value = "YES";
}
And then I examine the element using Firebug - the value is getting SET!
Once I take out the alert - no go!
How do I ensure that my mousedown event gets executed first? Or is this even the problem here????
mousedown is part of a click event.
Whatever you are doing with click events now should be moved to the submit event on the form. That way you can use mousedown, mouseover, or even click on the buttons to do whatever you want.
I have a voting script with an arrow system (upvotes and downvotes).If user clicks upvote, the arrow changes to the green arrow, meaning vote registered. If they click again, I want the arrow to revert back to the original image. However, using my code, it changes the image on the first like, but doesn't revert back on a second click.
if (like.src = 'vote_triangle.png') {
like.src = 'vote_triangle_like.png';
} else {
like.src = 'vote_triangle.png';
}
Use a more lenient if statement like:
if (like.src.indexOf('vote_triangle.png')!=-1) {
like.src = 'vote_triangle_like.png';
} else {
like.src = 'vote_triangle.png';
}
I know it's a very old thread, but I would like to add my findings here for future reference.
I found the following code wasn't working:
function swapImage() {
var element = document.getElementById("myImage");
if (element.src == "image1.png") {
element.src = "image2.png";
} else {
element.src = "image1.png"
}
}
Showing alerts containing the element.src taught me it contained the full path to the image in my local machine. Thus, the if statement had been always evaluated to false.
To fix that in a logical manner, what I did was get the attribute of the element, as the following code shows.
function swapImage() {
var element = document.getElementById("myImage");
if (element.getAttribute("src") == "image1.png") {
element.src = "image2.png";
} else {
element.src = "image1.png";
}
}
By using the function getAttribute("attributeName"), I was able to retrieve the path contained in the src relatively to the project directory.
I would suggest, instead of using img soruce as conditional statement, use a global variable, change its state once the upvote is clicked by say +1 and for downvotes -1.
//when 0, show upvote image, make it a global by declaring before any function
var UpVote = 0;
//when upvote clicked, when greater than 0, show down vote img
UpVote = UpVote +1 ;
//conditional logic for img source
if(UpVote > 0){
like.src = 'vote_triangle.png';
}
else{
like.src = 'vote_triangle_like.png';
}