jQuery: .after() is causing multiplication element duplication glitch? - javascript

Basically, I am getting an href value, then taking that value, creating a new element after the one im getting it from, then applying the href to the new one. The problem is, after every time I copy and paste this code, one for facebook, and one for twitter, as a share button, it multiplies from 2 to 3, showing 1 twitter button, and two facebook buttons. This has completely stumped me, never ran into this issue before.
$(document).ready(function () {
$('.mm').each(function () {
$('a', this).after('<br><a class="tw">twitter</a><br>');
var lnk = $(this).find('a').attr('href');
$('.tw', this).attr('href', lnk);
});
});
$(document).ready(function () {
$('.mm').each(function () {
$('a', this).after('<br><a class="fb">facebook</a><br>');
var lnk = $(this).find('a').attr('href');
$('.fb', this).attr('href', lnk);
});
});
Codepen: https://codepen.io/zachreynolds/pen/oEBMzz

It's because you are applying .each() 2 times.
You need to Merge your code into one .each() like below:-
$(document).ready(function () {
$('.mm').each(function () {
var lnk = $(this).find('a').attr('href');
$(this).find('a').after('<br><a class="tw" href="'+lnk+'">twitter</a><br><br><a class="fb" href="'+lnk+'">Facebook</a><br>');
});
});
Working example:-
$(document).ready(function () {
$('.mm').each(function () {
var lnk = $(this).find('a').attr('href');
$(this).find('a').after('<br><a class="tw" href="'+lnk+'">twitter</a><br><br><a class="fb" href="'+lnk+'">Facebook</a><br>');
});
});
html {
background-color: #eee;
}
.mm{background:#ccc;margin:5px}
body {
margin: 0 auto;
color: #323232;
max-width: 100%;
line-height: 1.5;
padding: 1em 3em;
background-color: #fff;
font-family: 'Roboto', serif;
}
h1 {line-height: 2;}
p{ font-size: 1.2em;}
pre {
padding: .5em;
color:#bada55; /* bright green */
display: block;
border-radius: 0.3em;
font-size:1em;
background-color: #000;}
}
code {
background-color: #eee;
font-size:.25em;
font-family:verdana;
}
a:link {color:#DB2929;text-decoration:underline;}
a:visited{color:green;text-decoration:none;}
a:hover{color:green;}
a:active{color:red;}
.tw,.fb{width:100px;height:33px;padding:7px;}
.tw {background:#09f}
.fb {background:#46a}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="cc-m-8497708420" class="j-module n j-rss ">
<div class="rssFeed">
<h3>sustainability</h3>
<div class="mm">
<span class="rssFeedTitle j-rss-feed-title">Trees that helped save America's farms during the Dust Bowl are now under threat</span><br><br>
>> Read More<br><br>
</div>
<div class="wrappedtext">(Tue, 06 Feb 2018)</div>
<div class="mm">
<span class="rssFeedTitle j-rss-feed-title">Can Money Grow on Trees? Across the world, businesses are making money by restoring forests and farmland.</span><br><br>
>> Read More<br><br>
</div>
<div class="wrappedtext">(Wed, 07 Feb 2018) </div>
</div>
</div>

Related

CSS style shows after refresh and then goes invisible with Knockout

So I have a new notification style ring and green circle with unread notifications in it this circle only is visible when you have new notifications.
when page is refreshed even if you dont have a notification the circle is visible for a second and then goes invisible
If there is a new notification still when refreshed circle shows up empty or with zero and then goes invisible and then with correct number
HTML:
<div class="bell">
<div class="unseen-notification-show" data-bind="visible: UnSeenMessagesCount() > 0, text: UnSeenMessagesCount()" style="display:none"></div>
</div>
CSS:
.unseen-notification-show {
content: '';
display: block !important;
position: absolute;
top: -10px;
right: -8px;
width: 17px;
height: 17px;
border: 1px solid #ffffff;
background-color: #8cdb16;
border-radius: 8px;
cursor: pointer;
z-index: 3;
color: white;
text-align: center;
line-height: 15px;
font-size: 11px;
font-family: 'Times New Roman', Times, serif;
}
self.searchModel = new AuthorizedSearchViewModel();
self.Header = ko.observable(new HeaderModel());
self.UnSeenMessagesCount = ko.observable(0);
self.Messages = ko.observableArray();
self.CanShowRemindProfile = ko.observable(false);
self.Remind = ko.observable(new RemindModel());
self.LoadUserInformation = function () {
$.post('/User/GetUserInfoForDashboardHeader',
function (response) {
InitTawkChat(response);
self.Header(new HeaderModel(response));
if ($('#accountId').length > 0) {
$('#accountId').html(response.accountId);
}
}, "json").done(function () { console.warn("loaderOff"); });
};
self.GetRemindProfile = function () {
self.CanShowRemindProfile(false);
$.post('/User/GetRemindProfile', function (result) {
if (result) {
self.CanShowRemindProfile(true);
self.Remind(new RemindModel(result));
}
});
};
self.GetMessages = function () {
$.post('/Messages/GetAll', {
page: 1,
pageSize: 4
}, function (result) {
var notifications = [];
_.map(result.Notifications, function (item) {
notifications.push(new MessageModel(item));
});
self.Messages(notifications);
self.UnSeenMessagesCount(result.UnseenNotifications);
});
};
Remove !important from display property in your css and let knockout inline handle display.
function viewModel(){
var self = this;
self.UnSeenMessagesCount = ko.observable();
self.initData = function(){
//dummy setTimeout for your ajax get.
setTimeout(function(){
self.UnSeenMessagesCount(4);
},1000);
}
}
var vm = new viewModel();
vm.initData();
ko.applyBindings(vm);
.unseen-notification-show {
content: '';
display: block;
position: absolute;
width: 17px;
height: 17px;
border: 1px solid #ffffff;
background-color: #8cdb16;
border-radius: 8px;
cursor: pointer;
z-index: 3;
color: white;
text-align: center;
line-height: 15px;
font-size: 11px;
font-family: 'Times New Roman', Times, serif;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<div class="bell">
<div class="unseen-notification-show" data-bind="visible: UnSeenMessagesCount() > 0, text: UnSeenMessagesCount()" style="display:none"></div>
</div>
Sounds like some loading issues. Try moving your css from being loaded in the top of the HTML, to be loaded in the bottom/footer.
What you want to do, is to hide the circle until the result is loaded (either 0 or 1,2,3,4.. and so on. Depending on the number of notifications).
In your div you got this line style="display:none"> which hides the circle. Thats good!
Now you should make sure that the style for .unseen-notification-show which contains display: block !important; that shows the circle - Should not be run before the calculation of the number to show is done.
One way could be to place the file that loads your css to the bottom of the HTML (like moving your <link rel="stylesheet" href="test.css" />). Or another way is to only use css for the hiding and then use javascript/jQuery for showing the cirle.
If this didn't help - then please provide the code you use to generate the number.
I think the issue is due to
self.UnSeenMessagesCount = ko.observable(0);
so when your modal is getting created it is initialized with value 0. So when you refresh the page initially it is 0 but when self.getMessage is called it updates your value.

JS reset function for 2 clipboards

Great day, I would like to ask for some advise please, im really new to html and css as well as java and putting all of them together is a bit hard for me so, i'm hoping for some advise.
I recently created a form, though i couldn't figure out how to reset all the function, like resetting the contain to its original form after im done copying it.
please the my codes and let me know what i can do. your help is greatly appreciated.
<html>
<head>
<style type="text/css">
/* Some Generic styles */
body {
text-align: center;
font-family: "Open Sans", Helvetica, Arial, sans-serif;
color: #023378;
line-height: 0.5;
background-color:#1E334F;
}
h1 {
margin: 0.5em auto 0.5em;
color: #71A4EB;
}
textarea,
button {
font-size: 1em;
font-family: "Open Sans", Helvetica, Arial, sans-serif;
}
textarea {
display: block;
margin: 0.5em auto 0.5em;
background: #CAD6E6;
resize: vertical;
}
[id="cleared"] {
margin-top: 4em;
}
textarea:focus {
border-color: #8fa423;
}
button {
position: relative;
padding: 8px 20px;
border: 0;
font-size: 0.835em;
text-transform: uppercase;
letter-spacing: 0.125em;
font-weight: bold;
color: #3F71B6;
background: #7DA9E6;
transition: background .275s;
}
button:hover,
button:focus {
background: #5275A5;
}
p {
margin-top: 3.25em;
font-size: .825em;
color: #777;
font-weight: bold;
letter-spacing: .01em
}
</style>
<h1>SH!N</h1>
<body>
<textarea id="to-copy" cols="80" rows="25" spellcheck="false">
SESA
Caller's Name:
Call back number:
Email Address:
Related case #s (case history):
Location, remote/hotel/office:
Application Name:
Number of Users Affected: Number of Users Affected: (Single User / Less than 5 users / 5 or more users)
What is the issue/problem:
When did the issue/problem begin:
Login id:
Error message (if any):
When was the last time it worked properly:
Have there been any changes to your PC since the last time it worked properly:
Have you changed your password recently:
Troubleshooting steps (detailed):
Additional Detail (links, screen shots etc.. :
</textarea><br>
<button id="copy" type="button">Copy<span class="copiedtext"aria-hidden="true"></span></button>
<textarea id="text" cols="80" rows="8" >
Resolution:
A - problem:
B - cause:
C - actions:
D - resolution:
</textarea><br>
<button onclick="copy()">Copy</button><br>
<SCRIPT TYPE="text/javascript">
var toCopy = document.getElementById( 'to-copy' ),
btnCopy = document.getElementById( 'copy' );
btnCopy.addEventListener( 'click', function(){
toCopy.select();
if ( document.execCommand( 'copy' ) ) {
btnCopy.classList.add( 'copied' );
var temp = setInterval( function(){
btnCopy.classList.remove( 'copied' );
clearInterval(temp);
}, 600 );
} else {
console.info( 'document.execCommand went wrong…' )
}
return false;
} );
function copy () {
var text = document.getElementById('text');
var range = document.createRange();
range.selectNode(text);
window.getSelection().addRange(range);
document.execCommand('copy');
}
</SCRIPT>
</body>
</html>
In order to make a form, you should not use textarea (or using it only as a part of a form, for instance to make a comment in a blog)
If you want to make a form, you must use form tag
<form id="myForm">Caller's name <input type="text" name="callerName"> ... </form>
https://www.w3schools.com/html/html_forms.asp
And then if you want to reset it, inside javascript :
document.getElementById("myForm").reset();
Your form does have id "myForm", you select this element and use reset() function on it which work on form.
PS: You should put your style in a CSS file and your script in a JS file.
EDIT :
If you want to copy it :
var myForm = document.getElementById('myForm');
var targetForm = document.getElementById('targetForm');
targetForm.innerHTML = myForm.innerHTML;
Offcourse you need to have a form tag with id set to targetForm.

Button click Triggers Text Below

I want to set up a functionality for a button that causes text to appear underneath it on click.
For example, when you click a button that says "Sign up now", text would appear underneath the button that says "Are you a member, yes or no?".
"Yes" and "No" would be links that bring you to a different page depending on how you answer.
My button code so far (just html and styling done):
<a href="/ticket-link" target="_blank" class="ticket-button">Sign Up
Now</a>
I'm new with this kind of functionality so any help would be greatly appreciated!
Thanks!
Adjust the href attribute as you want.
$('#btn').click(function() {
$('#modal').fadeIn();
});
a {
display: block;
text-decoration: none;
color: white;
background-color: #333;
width: 100px;
padding: 20px;
border-radius: 5px;
margin: 0 auto;
}
#modal {
width: 300px;
height: 120px;
background-color: #ccc;
border-radius: 5px;
margin: 0 auto;
display: none;
}
#modal h3 {
text-align: center;
padding: 10px;
}
#modal a {
width: 50px;
display: inline-block;
text-align: center;
margin: 0 auto;
height: 10px;
vertical-align: middle;
line-height: 10px;
}
.btns {
width: 200px;
margin: auto;
}
a:hover {
background-color: #666;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="/ticket-link" target="_blank" class="ticket-button" id='btn'>Sign Up Now</a>
<div id='modal'>
<h3>Are you a member?</h3>
<div class='btns'>
Yes
No
</div>
</div>
You could use the onClick function to unhide text, or elements, below it.
Sign Up Now
<span style="display:none;" id="text">This is some text :D</span>
simple way:
Sign Up Now
<script>
function confirmSignup(){
if(confirm("Are you sure?"))
{
window.location.href="http://somelocation.com/sign-up";
}
}
</script>
Like #Pety Howell said, you can use the onClick function to unhide the text. Here's a pretty straightforward way to do it with jQuery.
$(function() {
$('.link').on('click', function() {
$('.span').addClass('open');
});
});
.span {
display: none;
}
.open {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Click me
<span class="span">I'm hidden!</span>
Working fiddle: https://jsfiddle.net/3gr03yzn/4/
You could use jQuery toggle() function.
HTML :
<button id="member">
Are you Member ?
</button>
<div class="answer">
Yes<br />
No
</div>
JS :
$("#member").click(function() {
$(".answer").toggle();
});
CSS :
.answer {
display:none;
}
The working example on jsFiddle.
Hope this helps
Try this code.
please vote if this code helpful to you
function execute(){
var x = document.getElementById('link_list');
var y =document.getElementById('btn');
if(x.style.visibility==="hidden"){
y.style.visibility="hidden";
x.style.visibility="visible";
}
}
<button onclick="execute()" id="btn">sign up</button>
<div id="link_list" style="visibility:hidden">
Are you a member, <button onclick="window.open('http://sparrolite.blogspot.in')">Yes</button> or <button onclick="window.open('google.com')">no</button>
</div>
Most answers mentioned here either uses
jQuery or,
onclick attribute which is obtrusive javascript.
Here's how to achieve the desired behavior using vanilla, unobtrusive JavaScript.
window.onload = function() {
var button = document.querySelector('.ticket-button');
var info = document.querySelector('.info');
info.style.display = 'none';
var dispalyInfo = false;
button.onclick = function(e) {
e.preventDefault(); /* prevent page from navigating to a new page onclick */
if (dispalyInfo) {
info.style.display = 'none';
dispalyInfo = false;
} else {
info.style.display = 'initial';
dispalyInfo = true;
}
}
}
.ticket-button {
display: block;
}
Sign Up Now
<span class="info">Are you a member, yes or no?</span>
References:
Document.querySelector()
HTMLElement.style

Text slideshow with jQuery not functioning correctly when there's <br>

I'm trying to create a simple text slideshow which transits between a phrase to another and loop itself but when I added a break rule to the text, the slideshow doesn't seem to function correctly. It only works when the text is a single line. Your assistance would be greatly appreciated.
Here's the code and jsFiddle: http://jsfiddle.net/rezasan/fnbn8sbc/
//HTML
<div id="index_splashtext">
<h3>An<br/>Intimate<br/>Hideaway</h3>
<h3>A<br/>Paradise<br/>Preserved</h3>
</div>
//CSS
#index_splashtext {
width:311px;
margin:0 auto;
height: 330px;
margin-top: 25px;
text-align:center;
}
#index_splashtext h3 {
position: absolute;
font-size: 4.5em;
line-height: 1.2em;
font-family: "adobe-garamond-pro",sans-serif;
letter-spacing: 0.05em;
font-weight: 400;
margin-bottom: 70px;
color: red;
}
//jQuery
$(function(){
$('#index_splashtext h3:gt(0)').hide();
setInterval(function(){
$('#index_splashtext :first-child').fadeOut(2500)
.next('h3').fadeIn(2500)
.end().appendTo('#index_splashtext');},
8000);
});
You want to use $('#index_splashtext h3:first') instead of $('#index_splashtext :first-child'). In this case, :first-child is also being applied to the <br /> elements, so they get hidden but never faded back in:
$(function () {
$('#index_splashtext h3:gt(0)').hide();
setInterval(function () {
$('#index_splashtext h3:first').fadeOut(2500)
.next('h3').fadeIn(2500)
.end().appendTo('#index_splashtext');
},
8000);
});
jsFiddle example
well this is how i achieved your desired effect, and it is scalable too :)
html:
<div id="index_splashtext">
<h3></h3>
</div>
javascript:
$(function(){
var messages=[];
var counter=0;
var fadeInLength = 2500;
var fadeOutLength = 2500;
var hold = 1000;
messages.push('An<br />Intimate<br />Hideaway');
messages.push('A<br />Paradise<br />Preserved');
$('#index_splashtext h3').hide();
setInterval(function(){
$('#index_splashtext :first-child').
html(messages[counter]).
fadeIn(fadeInLength).
delay(hold).
fadeOut(fadeOutLength);
counter++;
if(counter > messages.length-1){counter=0;}
},fadeInLength+fadeOutLength+hold + 1000);
});

Drop Down Menu Issue

I am writing a drop-down menu for the school intranet site and I have created a rather strange issue. The sub-menus are offset from the selected menu y position by 36px.
Here's a excerpt of the code (please excuse the quality :D)
<html>
<head>
<style>
#navagationBar {
margin: 0;
padding: 0;
z-index: 30;
}
#navagationBar li {
list-style: none;
float: left;
font: bold 12px 'Arial';
margin-left: 10px;
width: 96px;
}
#navagationBar li a {
display: block;
margin: 0 1px 0 0;
padding: 4px 10px;
width: 136px;
color: #FFFFFF;
text-align: center;
text-decoration: none;
}
#navagationBar li a:hover {
background: #796952;
}
#navagationBar div {
position: absolute;
visibility: hidden;
background: transparent;
}
#navagationBar div a {
position: relative;
display: block;
padding: 5px 10px;
width: 136px;
white-space: nowrap;
text-align: left;
text-decoration: none;
background: #796952;
color: #FFF;
font: 9px "Arial";
}
#navagationBar div a:hover {
background: #969696;
color: #FFF;
}
#navagationBar a {
color: #FFF;
}
div.navagation {
background: #2d221c;
height: 28px;
}
div.sub {
left: 156px;
}
</style>
<!-- BG COLOR: #2d221c
FORERGROUND: #3c3429
HOVER: #796952
-->
<script>
var menuItem = 0;
var subItem = 0;
var timeLimit = 250;
var closeTimer = 0;
var closeSubTimer = 0;
// open menu
function openMenu(id) {
stopTimer();
// If a layer is already open close it
if (menuItem) {
menuItem.style.visibility = 'hidden';
}
// Then set the one clicked on by the user to be shown
menuItem = document.getElementById(id);
menuItem.style.visibility = 'visible';
}
function openSub(id) {
stopSubTimer();
// If a layer is already open close it
if (subItem) {
subItem.style.visibility = 'hidden';
}
subItem = document.getElementById(id);
subItem.style.visibility = 'visible';
}
function close() {
if (menuItem) {
menuItem.style.visibility = 'hidden';
}
}
function closeSub() {
if (subItem) {
subItem.style.visibility = 'hidden';
}
}
function startTimer() {
closeTimer = window.setTimeout(close, timeLimit);
}
function startSubTimer() {
closeSubTimer = window.setTimeout(closeSub, timeLimit);
}
// Stop timing
function stopTimer() {
if (closeTimer) {
window.clearTimeout(closeTimer);
closeTimer = null;
}
}
// TODO: Make more modular
function stopSubTimer() {
if (closeSubTimer) {
window.clearTimeout(closeSubTimer);
closeSubTimer = null;
}
}
// If the user click out, close teh box
document.onclick = close();
document.onclick = closeSub();
</script>
</head>
<body>
<div class="navagation">
<ul id="navagationBar">
<li>HSIE
<div id="menu0" onMouseOver="stopTimer()" onMouseOut="startTimer()">
Business Studies
<div class='sub' id="submenu0_0" onMouseOver="openSub('submenu0_0')" onMouseOut="startSubTimer()">
<a href='view.php?id=110'>Year 11</a>
<a href='view.php?id=109'>Year 12</a>
</div>
Commerce
<div class='sub' id="submenu0_1" onMouseOver="openSub('submenu0_1')" onMouseOut="startSubTimer()">
<a href='view.php?id=112'>Year 9</a>
<a href='view.php?id=111'>Year 10</a>
</div>
Geography
<div class='sub' id="submenu0_2" onMouseOver="openSub('submenu0_2')" onMouseOut="startSubTimer()">
<a href='view.php?id=48'>Year 7</a>
<a href='view.php?id=92'>Year 8</a>
<a href='view.php?id=105'>Year 9</a>
<a href='view.php?id=70'>Year 10</a>
<a href='view.php?id=69'>Year 11</a>
<a href='view.php?id=131'>Year 12</a>
</div>
History
<div class='sub' id="submenu0_3" onMouseOver="openSub('submenu0_3')" onMouseOut="startSubTimer()">
<a href='category.php?id=89'>Junior</a>
<a href='category.php?id=90'>Senior</a>
</div>
</div>
</li>
</ul>
</div>
</body>
</html>
Try putting the sub menu divs before the corresponding a tags (instead of putting these divs after them).
For instance, try this:
<div class='sub' id="submenu0_0" onMouseOver="openSub('submenu0_0')" onMouseOut="startSubTimer()">
<a href='view.php?id=110'>Year 11</a>
<a href='view.php?id=109'>Year 12</a>
</div>
Business Studies
Instead of this:
Business Studies
<div class='sub' id="submenu0_0" onMouseOver="openSub('submenu0_0')" onMouseOut="startSubTimer()">
<a href='view.php?id=110'>Year 11</a>
<a href='view.php?id=109'>Year 12</a>
</div>
DOM Access
First, you have to make absolutely sure to not access the DOM by getElementbyId(); before the whole page has loaded.
You have to invoke the script right before the closing body tag or wrap your whole code in one function and invoke it at the end, right before the closing body tag. This is Yahoo! and Google Front-End Development best practice.
Alternatively you could use JQuery's $(document).ready() function or another JavaScript library's document-loaded function. Using a library for addressing just this issue, however would be overkill.
Global Variables
By declaring var menuItem = 0; outside the function scope, you declare the variable as a global, which is a very bad thing! It will clutter your entire Web site's namespace. Declare variables inside a function to create a closure.
Also you don't want to initialise your menuItem variable with an integer, because you will reference an object later on (a DOM object). Albeit Javascript doesn't need types to be dclared and this will work, it is creating confusion with the reader of the code. Just use var menuItem; inside the function.
CSS Block Formatting Context
Try using display: inline or display: block with your HTML elements. Make sure to read and understand the W3C CSS Visual formatting model.
You have individual IDs for each sub level so you could add styling for each.
#submenu0_0 > a {top:0px;}
#submenu0_1 > a {top:25px;}
#submenu0_2 > a {top:50px;}
#submenu0_3 > a {top:75px;}
Is this due to quirks mode?
Try using a proper doctype like this:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
</body>
</html>

Categories

Resources