I have a javascript function, using jQuery, which manipulates a <div id="message"> to print error and status messages.
It looks like this:
function messageShow(msg, type) {
$('#message').addClass("message red");
$('#message').html(msg);
$("#message").slideDown(200, 0).fadeTo(200, 1);
setTimeout(function() {
$("#message").fadeTo(500, 0).slideUp(500, 0);
}, 5000);
//alert('asdasd');
}
The content of the div is only seen if I uncomment the alert(); line.
There is no redirect after this, so the page is not changed before the content is loaded.
I tried:
$('#message').html(msg, function() { ... });
Just to be sure, but that doesn't work either.
The div:
<div id="message"></div>
The css:
.message {
border-radius: 5px;
width: 100%;
height: 20px;
padding: 10px;
vertical-align: middle;
line-height: 20px;
}
.red {
background: #daa;
color: #855;
}
I do recomend you to use jquery delay function instead.
Try this:
function messageShow(msg, type) {
$('#message').addClass("message red");
$('#message').html(msg);
$("#message").slideDown(200, 0).fadeTo(200, 1).delay( 500 ).fadeTo(500, 0).slideUp(500, 0);
}
Related
My aim is for the users to click the button multiple times and on each click it changes the color and the wording on the button. I got the word and the color to change on the first and second click but it doesn't change when I click again. What am I doing wrong?
You can find my code below:
$(document).ready(function() {
$("button").click(function() {
$("#partyButton").text("Party Over!");
$(this).addClass("click").one("click", function() {
$("#partyButton").text("Party Time!");
$(this).removeClass();
});
});
});
button {
color: white;
font-family: 'Bungee';
background-color: #222;
border: none;
border-radius: 5px;
width: 25%;
padding: 20px;
cursor: pointer;
}
.click {
background-color: #0A8DAB;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="partyButton" type="button"> party time!</button>
You can achieve this By using toggleClass and check with .hasClass()
//button
$(document).ready(function (){
$("button").click(function (){
$(this).toggleClass("click").text($(this).hasClass('click') ? "Party Time":"Party Over!");
});
});
button{
color: white;
font-family: 'Bungee';
background-color:#222;
border: none;
border-radius: 5px;
width: 25%;
padding: 20px;
cursor: pointer;
}
.click{
background-color:#0A8DAB;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id = "partyButton" type = "button"> party time!</button>
Code Explanation:
$(this).toggleClass("click") this will toggle between class on each click
$(this).hasClass('click') check if this element has a class it return true/false .. you can also use it like if($(this).hasClass('click')){}else{}
() ? : ; shorthand if statment
Also Take care when you use removeClass() without assign any class it will remove all the classes for this element
The problem is you are registering an one time click event for the button while the button is clicked for the first time, which will detach the event once clicked. This is the reason you are not getting the event further. It is unnecessary and confusing
You just need the below implementation
$("#partyButton").click(function(){
if($(this).hasClass('click'))//check whether it party time or not
{
$(this).text("Party Time!").toggleClass('click');
}
else
{
$(this).text("Party Over!").toggleClass('click');
}
})
https://jsfiddle.net/n5hdg7tv/
For example:
$(function() {
$('#partyButton').on('click', function () {
var $button = $(this);
if($button.hasClass('click')) {
$button.removeClass('click').text('Party Time !');
} else {
$button.addClass('click').text('Party Over !');
}
})
});
I'm trying to change the contents of a div when it's hovered over using JQuery. I've seen answers on stack overflow, but I can't seem to get it working.
I've tried
$( "imgDiv" ).mouseover(
function() {
$("tdiv").textContent = "hovering";
},
function() {
$("tdiv").textContent = 'title';
}
);
I've also replaced "mouseover" with "hover". I've used a variable and the actual div in place of "imgDiv".
This is what my code looks like:
imgDiv = document.getElementById('imgDiv');
tDiv = document.getElementById('titleDiv');
$( "imgDiv" ).mouseover(
function() {
$("tdiv").textContent = "hovering";
}, function() {
$("tdiv").textContent = 'title';
}
);
body {
background: white;
padding: 20px;
font-family: Helvetica;
}
#imgDiv {
width: 100px;
height: 100px;
background-color: pink;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="imgDiv">
<div id=titleDiv>title</div>
</div>
You can use jQuery's .hover() function along with the .text() function to do what you want. Also, no need for document.getElementById:
$("#imgDiv").hover(
function() {
$("#titleDiv").text("hovering");
},
function() {
$("#titleDiv").text('title');
}
);
body {
background: white;
padding: 20px;
font-family: Helvetica;
}
#imgDiv {
width: 100px;
height: 100px;
background-color: pink;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="imgDiv">
<div id="titleDiv">title</div>
</div>
You can target the div with jQuery, and store it's original value. On mouseout, you can restore it. Also using mouseenter reduces the number of times the logic processes as mouseover will fire for every mouse move over the element.
var $titleDiv = $('#titleDiv');
$("#imgDiv")
.on('mouseenter', function() {
$titleDiv.data('originalText', $titleDiv.text());
$titleDiv.text('hovering');
})
.on('mouseout', function() {
$titleDiv.text($titleDiv.data('originalText'));
});
body {
background: white;
padding: 20px;
font-family: Helvetica;
}
#imgDiv {
width: 100px;
height: 100px;
background-color: pink;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="imgDiv">
<div id="titleDiv">title</div>
</div>
First of all, replace $("imgDiv") with $("#imgDiv") to get the element with id (#) imgDiv.
Then $("tdiv") doesn't exist, you probably mean $("div") to select a <div>tag in your DOM.
And finally, $("tdiv").textContent doesn't exist. You can try $("div").html() or $("div").text() to get the <div> tag content
--
Quick reminder : jQuery documentation on selectors
$("div") will select the <div> tags
$(".element") will select tags with class="element"
$("#element") will select tags with id="element"
You need to try like this
$( "#imgDiv" ).mouseover(function() {
$("#titleDiv").text("hovering");
}).mouseleave( function() {
$("#titleDiv").text('title');
});
body {
background: white;
padding: 20px;
font-family: Helvetica;
}
#imgDiv {
width: 100px;
height: 100px;
background-color: pink;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="imgDiv">
<div id=titleDiv>title</div>
</div>
Easy solution,
var s = document.getElementsByTagName('div');
function out() {
s[0].innerHTML = 'hello';
}
function ibn() {
s[0].innerHTML = 'Myname';
}
<div onmouseout = 'out()' onmouseenter = 'ibn()'> Myname </div>
You cannot call reference a dom with pure Javascript and them manipulate it with jQuery - it will not work.
Try this:
$( "#imgDiv" ).mouseover(function() {
$("#titleDiv").text("hovering");
});
The titleDiv id has to be referenced in your code using "#", then the id name.
Also, use $("#name_of_id").text("your content") instead of .textContent()
I can't seem to get my jquery <div id="NotificationDotOnNav" > {{NotificationNavDot}} </div> function to work!
Find below the helper file:
<template name="home">
<div id="NotificationDotOnNav" > {{NotificationNavDot}} </div>
</template>
Find below my helper file:
Template.home.helpers({
'NotificationNavDot': function () {
var numberOfNotifications = recipientsDetails.find({counts:1}).count();
if (numberOfNotifications > 0) {
$("#NotificationDotOnNav").css({ "visibility": "visible"});
alert("Testing!");
return;
}
else {
$("#NotificationDotOnNav").css({ "visibility": "hidden"});
}
},
});
When run, a popup with Testing! displays, clearly meaning the flow actually enters the if (numberOfNotifications > 0), however the $("#NotificationDotOnNav").css({ "visibility": "visible"}); fails to fire up!
What I find very strange is that, when copy & paste and run: $("#NotificationDotOnNav").css({ "visibility": "visible"}); in the browser console, it works!
Can someone kindly explain why it only fires-up when run in the browser console and not otherwise? Also kindly help me get this simple code to work.
I have included the relevant CSS file, in case this will help
#NotificationDotOnNav{
top: 10px;
float: right;
right: 5%;
visibility: hidden;
position: absolute;
z-index: 5;
min-width: 10px;
padding: 7px 7px;
border-radius: 20px;
background-color: #f54555ad;
}
Looking forward to your help!
Make sure your helper function execute after the Document Object Model (DOM) is ready and becomes safe to manipulate (this could be the reasons why your code runs when you type it in dev console but not when your run your js).
You can use $( document ).ready( handler ) (doc) for that.
Please consider a minimal reproducible example so we can help you out with more details.
By the way, you could also improve your code by caching the selector and using a ternary to write it more succinctly:
...
const numberOfNotifications = recipientsDetails.find({counts:1}).count();
const elm = $("#NotificationDotOnNav") // query the DOM just once
numberOfNotifications > 0 ? elm.show() : elm.hide()
...
Try it like this:
Template.home.helpers({
'NotificationNavDot': function () {
var numberOfNotifications = recipientsDetails.find({counts:1}).count();
if (numberOfNotifications > 0) {
$("#NotificationDotOnNav").css('opacity', '1');
alert("Testing!");
return;
} else {
$("#NotificationDotOnNav").css('opacity', '0');
}
}
});
Also change your CSS code:
#NotificationDotOnNav {
top: 10px;
float: right;
right: 5%;
opacity: 0; /* this has been changed */
position: absolute;
z-index: 5;
min-width: 10px;
padding: 7px 7px;
border-radius: 20px;
background-color: #f54555ad;
}
I found a walk around the issue that works.
Find below the changes that I've made to enable the code to work.
Find below updates I've made to my HTML code:
<template name="home">
<span id="NotificationDotOnNav" class="badge animated"> {{NotificationNavDot}} </span>
</template>
Find below my helper file:
Template.home.helpers({
'NotificationNavDot': function () {
var numberOfNotifications = recipientsDetails.find({counts:1}).count();
if (numberOfNotifications > 0 ) {
$("#NotificationDotOnNav").css({"visibility": "visible"});
return 0;
}
else {
$("#NotificationDotOnNav").css({ "visibility": "hidden"});
}
}
});
Find below my CSS:
#NotificationDotOnNav{
top: 11px;
float: right;
right: 10%;
height: 13px;
width: 1px;
position: fixed;
visibility: hidden;
z-index: 9;
font-size: xx-small;
color: #f5455500;
background-color: #f54555b5;
}
Nevertheless Id like to thank everyone for their contributions.
Duplicate:
Yes it is but a little bit different from this.
I'm using jQuery 3.1.0 This is my code:
$(document).ready(function () {
ToggleAsideBar();
});
function ToggleAsideBar(){
$(".ah-sidebar-toggle").click(function(){
let toggleSize = $(".ah-logo").width() == 230 ? "50px" : "230px";
$(".ah-logo").animate(
{ width: toggleSize },200,"linear",function () {alert("Animation Complete!");'}
);
});
}
Problem:
In my case, alert show before the animation starts. I want to show alert after the animation completed. Any thoughts what I am doing wrong in above code?
Live Example:
jsfiddle
You had a collision between jquery's animation and css's transition.
If you decide to use animate - you should remove the transition lines from your css file.
Here is a working version (without the transition in your css):
$(document).ready(function () {
ToggleAsideBar();
});
function ToggleAsideBar(){
//Get width of browser
$(".ah-logo").click(function(){
let toggleSize = $(".ah-logo").width() == 230 ? "50px" : "230px";
$(".ah-logo").animate(
{ width: toggleSize },200,"swing"
).promise().done(function(){
alert("Animation Complete!");
});
});
}
.ah-logo {
width: 230px;
float: left;
font-weight: 600;
font-size: 16px;
text-align: center;
overflow: hidden;
}
a {
line-height: 50px;
display: block;
}
<script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
<div class="ah-logo">
Admin
</div>
I am trying to create an array that holds all pending error messages that shows up on the DOM (Using jquery for that) and then loop through the array to see if there is any error messages to call, and if so remove them after executing them.
My problem is that I can't figure out how to push a function into an array and then execute it. This is what I have so far:
var dialogQueue = []
dialogQueue.push(errorCall("test", "test", "test", "test"));
for (var queueNum = 1, 1 < dialogQueue.length, 1++) {
alert(dialogQueue[1])
}
And if it helps, my code for showing the error messages:
function dialogShow() {
$(".dialog-con").css("display", "block").css("background", "rgba(0,0,0,.8)")
$(".body-wrapper").addClass("errorFilter");
$(".dialog-anim").animate({
opacity: 1,
marginTop: "-=20px"
})
setTimeout(function () {
$(".errorFilter").addClass("blur");
}, 100);
}
function dialogHide() {
$(".dialog-con").css("background", "rgba(0,0,0,.0")
$(".body-wrapper").removeClass("blur");
$(".dialog-anim").animate({
opacity: 0,
marginTop: "-=25px"
}, 300)
setTimeout(function () {
$(".dialog-con").css("display", "none");
$(".body-wrapper").removeClass("errorFilter");
// Code for removing the function from the array after pushing OK on the dialog
}, 1000);
}
function errorCall(title, sub, text, code) {
$(".dialog .title").text(title);
$(".dialog .subtitle").text(sub);
$(".dialog .text").html(text);
$(".dialog .error-code").html(code);
dialogShow();
}
I'll give you a fiddle with the full errorCall() function in action:
function dialogShow() {
$(".dialog-con").css("display", "block").css("background", "rgba(0,0,0,.8)")
$(".body-wrapper").addClass("errorFilter");
$(".dialog-anim").animate({
opacity: 1,
marginTop: "-=20px"
})
setTimeout(function () {
$(".errorFilter").addClass("blur");
}, 100);
}
function dialogHide() {
$(".dialog-con").css("background", "rgba(0,0,0,.0")
$(".body-wrapper").removeClass("blur");
$(".dialog-anim").animate({
opacity: 0,
marginTop: "-=25px"
}, 300)
setTimeout(function () {
$(".dialog-con").css("display", "none");
$(".body-wrapper").removeClass("errorFilter");
}, 1000);
}
function errorCall(title, sub, text, code) {
$(".dialog .title").text(title);
$(".dialog .subtitle").text(sub);
$(".dialog .text").html(text);
$(".dialog .error-code").html(code);
dialogShow();
}
errorCall("Hello stackoverflow!","This is how my error message dialog looks!","Blah blah blah blah","Code code code");
.dialog-con {
height: 100%;
display: none;
position: fixed;
width: 100%;
background-color: rgba(0, 0, 0, .0);
z-index: 50;
transition: ease 300ms;
}
.dialog-anim {
width: 100%;
height: 100%;
display: none;
display: flex;
flex-direction: column;
justify-content: center;
opacity: 0;
margin-top: -20px;
}
.dialog {
margin: auto;
padding: 12px 27px;
background: white;
border-radius: 3px;
width: 520px;
transform: translateY(30px)
}
.dialog .title-con {
margin-bottom: 25px;
}
.dialog .title {
font-size: 35px;
padding-bottom: 7px;
}
.dialog .error-code {
margin-top: 15px;
color: rgba(0, 0, 0, .6);
font-family: "Courier New", Courier, monospace
}
.dialog .subtitle {
font-size: 17px;
color: rgba(0, 0, 0, 0.4);
}
.dialog .text {}
.dialog .button-con {
margin-top: 25px;
}
.dialog button {
margin: auto;
float: right;
color: white;
border: none;
padding: 9px 37px;
background: #10b5ff;
text-transform: uppercase;
font-weight: bold;
border-radius: 3px;
}
.dialog button:hover {
background: black;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dialog-con">
<div class="dialog-anim">
<div class="dialog">
<div class="title-con">
<div class="title">Error Message Title</div>
<div class="subtitle"></div>
</div>
<div class="text-con">
<div class="text">Error Message</div>
<div class="error-code"></div>
</div>
<div class="button-con" onclick="dialogHide()">
<button>Ok</button>
</div>
</div>
</div>
</div>
(The ok button displacement is a result of the tiny viewport, ignore it.)
So the reason I want to do this is that in the event that something triggers multiple errors, they get pushed to the array and shown one after one (Pressing OK shows the next one etc).
You need to create a function wrapper to store them in the array. As it stands you're invoking errorCall as you push it to the array. Try this code instead:
var dialogQueue = []
dialogQueue.push(
function () {
errorCall("test", "test", "test", "test")
}
);
for (var queueNum = 0, 1 < dialogQueue.length, queueNum++) {
alert( dialogQueue[queueNum]() );
}
You also wanted to remove after execution, so could do it like this instead:
while(dialogQueue.length > 0) {
alert( dialogueQueue[0]() );
dialogueQueue.shift();
}
Here's a simplified example:
var funcArr = [];
funcArr.push( console.log("Cat") );
// This immediately calls console.log, logging "cat". After console.log is
// evaluated we push its return value `undefined`
// Instead, we wrap the console.log in an anonymous function. This gives us
// a function which will execute what we desire when it is called.
funcArr.push( function() { console.log("cat"); } );
// there is nothing to invoke now, because we are creating a new function.
// now if we:
console.log( funcArr );
// we get: [function anonymous()]
// So if we say:
funcArr[0];
// this will evaluate to:
function() {
console.log("cat");
};
// Therefore invoking funcArr[0] calls an anonymous function, which runs
// the function we actually wanted to run.
funArr[0]();
An alternative to ChadF's approach would be to instantiate a function and call a method on it when you want to show the message.
// Your base function
function error(a, b, c, d) {
this.show = function() {
alert(a + " " + b + " " + c + " " + d);
};
}
var dialogQueue = [];
// Creating an instance of "error"
dialogQueue.push(new error("test", "test2", "test3", "test4"));
dialogQueue.push(new error("testing again", "test2", "test3", "test4"));
alert("Data finished pushing");
for (var i = 0; i < dialogQueue.length; i++) {
// Calling the "show" method from "error"
dialogQueue[i].show();
}
you can push the args onto the array, and use that to execute the function. you can use apply to call a given function with a set of arguments.
like this:
dialogQueue=[];
//fill the queue with arguments
dialogQueue.push([1,2,3,4]);
dialogQueue.push(["test","test","test","test"]);
dialogQueue.push(["bla","bla","bla","bla"]);
//fire off everything in the queue
var len=dialogQueue.length;
for (i=0;i<len;i++) {
//pop off the args, and use apply to call them
var args=dialogQueue.pop();
errorCall.apply(this, args);
}