Notification alerts not working - javascript

I need to setup notification alerts for my website. I'm using this simple notification script. I have test it on my website like this.
<div id="notifications">
<div class="alert alert-danger" role="alert">
<a class="button close" style="padding-left: 10px;" href="#">×</a>
<i class="fa fa-info-circle "></i>
Thanks
</div>
</div>
Styles
#notifications {
cursor: pointer;
position: fixed;
right: 0;
z-index: 9999;
bottom: 0;
margin-bottom: 22px;
margin-right: 15px;
max-width: 300px;
}
Script
$( document ).ready(function() {
Notify = function(text, callback, close_callback, style) {
var time = '10000';
var $container = $('#notifications');
var icon = '<i class="fa fa-info-circle "></i>';
if (typeof style == 'undefined' ) style = 'warning'
var html = $('<div class="alert alert-' + style + ' hide">' + icon + " " + text + '</div>');
$('<a>',{
text: '×',
class: 'button close',
style: 'padding-left: 10px;',
href: '#',
click: function(e){
e.preventDefault()
close_callback && close_callback()
remove_notice()
}
}).prependTo(html)
$container.prepend(html)
html.removeClass('hide').hide().fadeIn('slow')
function remove_notice() {
html.stop().fadeOut('slow').remove()
}
var timer = setInterval(remove_notice, time);
$(html).hover(function(){
clearInterval(timer);
}, function(){
timer = setInterval(remove_notice, time);
});
html.on('click', function () {
clearInterval(timer)
callback && callback()
remove_notice()
});
}
});
The notification is appearing correctly because of css styling. But the script is not working. If I click close icon on notification, it's not closing. When I reload the page, it stays on the(auto closing is also not working) What ami I missing in my script?

Your requirements are a bit difficult to understand. You refer to the "notification" appearing correctly, but the only thing I see appearing is x Thanks in the bottom-right corner. However, that's not a notification, it's coming from your markup. It has no event associated with it, so nothing will happen when it is clicked.
Your main issue seems to be that you are defining something called Notify, but then not doing anything with it. To help you resolve this, please see the snippet below. It's probably not exactly what you want, but I think it's a lot closer.
$( document ).ready(function() {
Notify = function(text, callback, close_callback, style) {
var time = '10000';
var $container = $('#notifications');
var icon = '<i class="fa fa-info-circle "></i>';
if (typeof style == 'undefined' ) style = 'warning';
var html = $('<div class="alert alert-' + style + ' hide">' + icon + " " + text + '</div>');
$('<a>', {
text: '×',
class: 'button close',
style: 'padding-left: 10px;',
href: '#',
click: function(e) {
e.preventDefault();
e.stopPropagation();
close_callback();
remove_notice();
}
}).prependTo(html);
$container.prepend(html);
html.removeClass('hide').hide().fadeIn('slow');
function remove_notice() {
// html.stop().fadeOut('slow').remove()
html.fadeOut('slow', function() {
$(this).remove();
});
}
var timer = setInterval(remove_notice, time);
$(html).hover(function() {
setMessage('You hovered over me.');
clearInterval(timer);
}, function(){
if (parseInt(html.css('opacity')) === 1 ) {
// element is not currently being faded out
setMessage('You stopped hovering over me.');
timer = setInterval(remove_notice, time);
}
});
html.on('click', function() {
clearInterval(timer);
callback && callback();
remove_notice();
});
}
var notification = new Notify('This is a notification.', function() {
setMessage('You clicked my text.');
}, function() {
setMessage('You clicked my "x".');
});
});
function setMessage(messageText) {
$('#testMessage').text(messageText);
}
#notifications {
cursor: pointer;
position: fixed;
right: 0;
z-index: 9999;
bottom: 0;
margin-bottom: 22px;
margin-right: 15px;
max-width: 300px;
}
#testMessage {
position: fixed;
right: 0;
z-index: 9999;
top: 0;
margin-top: 22px;
margin-right: 15px;
max-width: 300px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/notify/0.4.2/notify.min.js"></script>
<div id="testMessage"></div>
<div id="notifications">
<!-- <div class="alert alert-danger" role="alert">
<a class="button close" style="padding-left: 10px;" href="#">×</a>
<i class="fa fa-info-circle "></i>
Thanks
</div> -->
</div>

Related

jQuery show / hide notification if read

I'm trying to show/hide the .notification indicator when all of the .activity__item is marked as read. They can be marked read by clicking each individual item's .activity__button, or by clicking the button to mark all item's as read.
Using the function below I tried identifying whether each item has received the read state (getting the .activity__button--read class) and then hiding the notification if all of the items have been read. This doesn't seem to work here.
Is there an efficient way to show/ hide the notification indicator when all items have been read either by
Clicking them individually or
Marking all as read by clicking
the button?
$(function() {
if (!$(".activity__button").not(".activity__button--read").length) {
$(this).closest(".activity__header").find(".notification").hide();
} else {
$(this).closest(".activity__header").find(".notification").show();
} });
var open = 'fas fa-envelope-open';
var close = 'fas fa-envelope';
$(".activity__button[data-status]").off().on('click', function() {
var status = $(this).data('status');
if (status == 'unread') {
$(this).data('status', 'read').empty().html('<i class="' + open + '"></i>').addClass('activity__button--read');
$(this).closest(".activity__item").addClass('activity__item--read');
} else {
$(this).data('status', 'unread').empty().html('<i class="' + close + '"></i>').removeClass('activity__button--read');
$(this).closest(".activity__item").removeClass('activity__item--read');
}
});
$('.mark').off().on('click', function() {
var status = $(this).data('status');
if (!status || status == 'unread') {
$(this).closest(".activity__header").find(".notification").hide();
$(this).html('Mark all unread').data('status', 'read');
$(".activity__button[data-status]").each(function() {
$(this).data('status', 'read').empty().html('<i class="' + open + '"></i>').addClass('activity__button--read');
$(this).closest(".activity__item").addClass('activity__item--read');
});
} else {
$(this).html('Mark all read').data('status', 'unread');
$(this).closest(".activity__header").find(".notification").show();
$(".activity__button[data-status]").each(function() {
$(this).data('status', 'unread').empty().html('<i class="' + close + '"></i>').removeClass('activity__button--read');
$(this).closest(".activity__item").removeClass('activity__item--read');
$(this).closest(".activity__header").find(".notification").show();
});
}
});
$(function() {
if (!$(".activity__button").not(".activity__button--read").length) {
$(this).closest(".activity__header").find(".notification").hide();
} else {
$(this).closest(".activity__header").find(".notification").show();
}
});
.activity__header {
display: flex;
}
.activity__item {
position: relative;
height: 100px;
width: 300px;
border: 1px solid whitesmoke;
margin-top: -1px;
}
.activity__button {
cursor: pointer;
padding: 1rem;
font-size: 21px;
}
.activity__button svg {
color: #f8971d;
}
.activity__button.activity__button--read svg {
color: #47a877;
}
.activity__item--read {
background: #fafafa !important;
}
button {
padding: 12px;
margin: 1rem;
}
.notification {
width: 10px;
height: 10px;
border-radius: 50%;
background-color: #cb6f74;
color: #fff;
font-size: 10px;
font-weight: 600;
}
<script src="https://pro.fontawesome.com/releases/v5.8.1/js/all.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="activity__header">
<button class="mark" data-status="unread">Mark as Read</button>
<div class="notification"></div>
</div>
<div>
<div class="activity__item">
<div class="activity__button" data-status="unread"><i class="fas fa-envelope"></i>
</div>
</div>
<div class="activity__item">
<div class="activity__button" data-status="unread"><i class="fas fa-envelope"></i>
</div>
</div>
<div class="activity__item activity__item--read">
<div class="activity__button activity__button--read" data-status="read">
<i class="fas fa-envelope-open"></i>
</div>
</div>
<div class="activity__item">
<div class="activity__button" data-status="unread">
<i class="fas fa-envelope"></i>
</div>
</div>
</div>
</div>
data-status"read"`?
One way would be to check the state of all items each time they are updated
You could use a function like this
function updateNotificationIcon(){
var $activity_items = $('.activity__item'),
all_read = true;
// Loop through each .activity__item
$activity_items.each(function(){
// If item does NOT have the "read" class, set all_read to false
if(!$(this).hasClass('activity__item--read')){
all_read = false;
}
});
if(all_read){
$('.notification').hide();
}else{
$('.notification').show();
}
}
Then just run that function after each change to one of the item's "read" state
In your case I would update your javascript as so:
var open = 'fas fa-envelope-open';
var close = 'fas fa-envelope';
$(".activity__button[data-status]").off().on('click', function() {
var status = $(this).data('status');
if (status == 'unread') {
$(this).data('status', 'read').empty().html('<i class="' + open + '"></i>').addClass('activity__button--read');
$(this).closest(".activity__item").addClass('activity__item--read');
} else {
$(this).data('status', 'unread').empty().html('<i class="' + close + '"></i>').removeClass('activity__button--read');
$(this).closest(".activity__item").removeClass('activity__item--read');
}
// Add here
updateNotificationIcon();
});
$('.mark').off().on('click', function() {
var status = $(this).data('status');
if (!status || status == 'unread') {
$(this).closest(".activity__header").find(".notification").hide();
$(this).html('Mark all unread').data('status', 'read');
$(".activity__button[data-status]").each(function() {
$(this).data('status', 'read').empty().html('<i class="' + open + '"></i>').addClass('activity__button--read');
$(this).closest(".activity__item").addClass('activity__item--read');
});
} else {
$(this).html('Mark all read').data('status', 'unread');
$(this).closest(".activity__header").find(".notification").show();
$(".activity__button[data-status]").each(function() {
$(this).data('status', 'unread').empty().html('<i class="' + close + '"></i>').removeClass('activity__button--read');
$(this).closest(".activity__item").removeClass('activity__item--read');
$(this).closest(".activity__header").find(".notification").show();
});
}
// Add here
updateNotificationIcon();
});
$(function() {
if (!$(".activity__button").not(".activity__button--read").length) {
$(this).closest(".activity__header").find(".notification").hide();
} else {
$(this).closest(".activity__header").find(".notification").show();
}
});
function updateNotificationIcon() {
var $activity_items = $('.activity__item'),
all_read = true;
// Loop through each .activity__item
$activity_items.each(function() {
// If item does NOT have the "read" class, set all_read to false
if (!$(this).hasClass('activity__item--read')) {
all_read = false;
}
});
if (all_read) {
$('.notification').hide();
} else {
$('.notification').show();
}
}

why my h1 title hides behind input box when slideUp executes

I have the following page, which is a wikisearch page that queries multiple wikipidia pages for the search term. The page has the title and input box somewhere around the middle; however, when I click on the botton, the title slides up, and so the input box. But the input box slides all way up covering the title. I think!... how can I prevent the inputbox from covering the title? or make the title stays at the top of page? Thanks
$(document).ready(function() {
//bringing focus to search box
window.load = function() {
document.getElementById("search-box").focus();
};
//listener for search button
$("#search").click(function() {
$("#title").slideUp(3000);
// $("#title").css("text-align", "left");
search();
});
function search() {
//grabbing the id of search result div
var srchResult = document.getElementById("results");
//string entered by user for search
var searchStr = document.getElementById("search-box").value;
//replace space with _ in search query
searchStr = searchStr.replace(" ", "_");
console.log(searchStr);
$.ajax({
url: "https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=" + searchStr + "&prop=info&inprop=url&utf8=&format=json",
dataType: "jsonp",
success: function(response) {
if (response.query.searchinfo.totalhits === 0) {
showError(searchStr);
} else {
displayResults(response);
}
},
error: function() {
alert("Something went wrong.. <br>" +
"Try again!");
}
});
function displayResults(response) {
console.log(response.query);
var search = response.query.search;
var srchLength = response.query.search.length;
srchResult.innerHTML = "";
// console.log(srchResult.innerHTML);
//pulling title and searchbox to top
// $("#title").css("margin-top:", "10px !important");
for (var i = 0; i < srchLength; i++) {
srchResult.innerHTML += '<div class="output"><h4>' + search[i].title + ' </h4><p>' + search[i].snippet + '</p></div>';
}
}
return false;
}
function showError(search) {
srchResult.innerHTML = '<div class="output text-center"><h4>No Search result for: ' + search + '</h4></div>';
}
});
body {
background-color: #495444;
}
search-input {
width: 90%;
}
center {
align-left: auto;
align-right: auto;
text-align: center;
}
.output {
background-color: white;
border-color: black;
border-width: 1px;
border-style: solid;
opacity: 0.5;
margin-top: 10px;
}
h1 {
margin-top: 200px;
color: #1484e5;
font-family: 'Josefin Sans', sans-serif;
font-size: 50px;
padding-bottom: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://fonts.googleapis.com/css?family=Josefin+Sans" rel="stylesheet">
<div class="container ">
<h1 id="title" class="text-center"><strong>WikiSearch</strong></h1>
<div id="input" class="input-group col-lg-8 offset-lg-2 col-md-8 offset-md-2 col-xs-12">
<input id="search-box" type="text" class="form-control" placeholder="Search Wikipidia Pages!..." />
<button id="search" class="btn btn-primary" onclick="#">Search</button>
</div>
<div id="results" class="col-lg-8 offset-lg-2">
</div>
</div>
Insted of using $('#title').slideUp(3000) try use $('#title').animate({'margin-top': '0'}, 3000);
Then the title will remain.
Also, you might want to remove onclick="#" from <button id="search" class="btn btn-primary" onclick="#">Search</button>
Example below.
$(document).ready(function() {
//bringing focus to search box
window.load = function() {
document.getElementById("search-box").focus();
};
//listener for search button
$("#search").click(function() {
$('#title').animate({'margin-top': '0'}, 3000);
//$("#title").slideUp(3000);
// $("#title").css("text-align", "left");
search();
});
function search() {
//grabbing the id of search result div
var srchResult = document.getElementById("results");
//string entered by user for search
var searchStr = document.getElementById("search-box").value;
//replace space with _ in search query
searchStr = searchStr.replace(" ", "_");
$.ajax({
url: "https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=" + searchStr + "&prop=info&inprop=url&utf8=&format=json",
dataType: "jsonp",
success: function(response) {
if (response.query.searchinfo.totalhits === 0) {
showError(searchStr);
} else {
displayResults(response);
}
},
error: function() {
alert("Something went wrong.. <br>" +
"Try again!");
}
});
function displayResults(response) {
var search = response.query.search;
var srchLength = response.query.search.length;
srchResult.innerHTML = "";
// console.log(srchResult.innerHTML);
//pulling title and searchbox to top
// $("#title").css("margin-top:", "10px !important");
for (var i = 0; i < srchLength; i++) {
srchResult.innerHTML += '<div class="output"><h4>' + search[i].title + ' </h4><p>' + search[i].snippet + '</p></div>';
}
}
return false;
}
function showError(search) {
srchResult.innerHTML = '<div class="output text-center"><h4>No Search result for: ' + search + '</h4></div>';
}
});
body {
background-color: #495444;
}
search-input {
width: 90%;
}
center {
align-left: auto;
align-right: auto;
text-align: center;
}
.output {
background-color: white;
border-color: black;
border-width: 1px;
border-style: solid;
opacity: 0.5;
margin-top: 10px;
}
h1 {
margin-top: 200px;
color: #1484e5;
font-family: 'Josefin Sans', sans-serif;
font-size: 50px;
padding-bottom: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://fonts.googleapis.com/css?family=Josefin+Sans" rel="stylesheet">
<div class="container ">
<h1 id="title" class="text-center"><strong>WikiSearch</strong></h1>
<div id="input" class="input-group col-lg-8 offset-lg-2 col-md-8 offset-md-2 col-xs-12">
<input id="search-box" type="text" class="form-control" placeholder="Search Wikipidia Pages!..." />
<button id="search" class="btn btn-primary">Search</button>
</div>
<div id="results" class="col-lg-8 offset-lg-2">
</div>
</div>
Add this to the h1 class
h1 {
z-index: 1000;
}
Now let's say you needed something to then go on top of the header, you'd give that element's class a z-index of something higher than 1,000, so maybe 1,001! If you needed something to go behind, simply make it 999 or lower. Using 1,000 gives you a lot of free range in either direction (+/-) to work with.

Removing a bootstrap popover dynamically using jquery

This following works when a list item is selected and then hovered and a popover is shown. But when I try to remove popover data attributes from list tag, all the tag removes but the popover does not remove. How to remove the popover such that when an item is not selected, the popover is not shown?
/* Latest compiled and minified JavaScript included as External Resource */
// Checked list box items
$(function() {
$('.list-group.checked-list-box .list-group-item').each(function() {
// Settings
var $widget = $(this),
$checkbox = $('<input type="checkbox" class="hidden" />'),
color = ($widget.data('color') ? $widget.data('color') : "primary"),
style = ($widget.data('style') == "button" ? "btn-" : "list-group-item-"),
settings = {
on: {
icon: 'glyphicon glyphicon-check'
},
off: {
icon: 'glyphicon glyphicon-unchecked'
}
};
$widget.css('cursor', 'pointer')
$widget.append($checkbox);
// Event Handlers
$widget.on('click', function() {
$checkbox.prop('checked', !$checkbox.is(':checked'));
$checkbox.triggerHandler('change');
updateDisplay();
});
$checkbox.on('change', function() {
var id = $(this).closest('li').attr('id');
var isChecked = $checkbox.is(':checked');
if (isChecked) addPopOver(id);
else removePopOver(id);
updateDisplay();
});
function addPopOver(id) {
id = "#" + id;
$(id).attr('data-toggle', "popover");
$(id).attr('data-trigger', "hover");
$(id).attr('data-original-title', $(id).text());
$(id).attr('data-content', "(No items selected)");
$('[data-toggle=popover]').popover();
}
function removePopOver(id) {
id = "#" + id;
$(id).removeAttr("data-toggle");
$(id).removeAttr("data-trigger");
$(id).removeAttr("data-original-title");
$(id).removeAttr("data-content");
}
// Actions
function updateDisplay() {
var isChecked = $checkbox.is(':checked');
// Set the button's state
$widget.data('state', (isChecked) ? "on" : "off");
// Set the button's icon
$widget.find('.state-icon')
.removeClass()
.addClass('state-icon ' + settings[$widget.data('state')].icon);
// Update the button's color
if (isChecked) {
$widget.addClass(style + color + ' active');
} else {
$widget.removeClass(style + color + ' active');
}
}
// Initialization
function init() {
if ($widget.data('checked') == true) {
$checkbox.prop('checked', !$checkbox.is(':checked'));
}
updateDisplay();
// Inject the icon if applicable
if ($widget.find('.state-icon').length == 0) {
$widget.prepend('<span class="state-icon ' + settings[$widget.data('state')].icon + '"></span>');
}
}
init();
});
$('#get-checked-data').on('click', function(event) {
event.preventDefault();
var checkedItems = {},
counter = 0;
$("#check-list-box li.active").each(function(idx, li) {
checkedItems[counter] = $(li).text();
counter++;
});
$('#display-json').html(JSON.stringify(checkedItems, null, '\t'));
});
});
/* Check Box For item required */
.state-icon {
left: -5px;
}
.list-group-item-primary {
color: rgb(255, 255, 255);
background-color: rgb(66, 139, 202);
}
/* DEMO ONLY - REMOVES UNWANTED MARGIN */
.well .list-group {
margin-bottom: 0px;
}
.list-inline>li {
display: inline-block;
padding-right: 12px;
padding-left: 20px;
margin-bottom: 3px;
font-size: 17px;
}
#check-list-box {
padding: 10px;
}
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<ul id="check-list-box" class="list-group checked-list-box list-inline ">
<li class="list-group-item event-item" id="venue" data-color="danger">Venue</li>
<li class="list-group-item event-item" id="catering" data-color="info">Catering</li>
<li class="list-group-item event-item" id="desserts" data-color="warning">Desserts</li>
<li class="list-group-item event-item" id="photographer" data-color="success">Photographer</li>
<li class="list-group-item event-item" id="bus" data-color="danger">Party buses</li>
<li class="list-group-item event-item" id="castles" data-color="danger">Bouncy Castles</li>
<li class="list-group-item" data-color="danger">Other</li>
<!--<input type="textbox" name ="other" >-->
</ul>
You could use .popover('destroy').
function removePopOver(id) {
id = "#" + id;
$(id).popover('destroy')
}
To destroy the shown popover you can use the following code-snippet:
function removePopOver(id) {
id = "#" + id;
$(id).popover('dispose'); // JQuery > 4.1
// $(id).popover('destroy'); // JQuery < 4.1
}
You can also remove all created popovers from your DOM via .popover class (of course each popover has its own id, so by knowing the IDs you can be more precise)
$('.popover').remove();

How to pause and start gif using jQuery AJAX

I am a student and I am trying to start, pause and start a gif when a user clicks the gif, however I am stuck on how to add in this click function. I know that the the gif version of the object is .images.fixed_height.url and the still image is .images.fixed_height_still.url . If I try to append like below $(this) I get that images is undefined. How would I go by doing this? Currently 10 gifs show when you click the category. Thank you for any help in advance.
Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Giphy</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<style>
body {
background-image: url('http://www.efoza.com/postpic/2011/04/elegant-blue-wallpaper-designs_154158.jpg');
width: 100%;
}
button {
padding: 0 2%;
margin: 0 2%;
}
h4 {
font-size: 165%;
font-weight: bold;
color: white;
}
.container {
background-color: rgba(0, 0, 0, 0.2);
max-width: 1000px;
width: 100%;
}
.btn {
margin-top: 2%;
margin-bottom: 2%;
font-size: 125%;
font-weight: bold;
}
.guide {
padding: 3% 0 0 0;
}
.tag-row {
padding: 3% 0 0 0;
}
.category-row {
padding: 3% 0 ;
}
#photo {
padding-bottom: 3%;
}
</style>
</head>
<body>
<div class="container">
<div class="row text-center guide"><h4>Click a category and see the current top 10 most popular giphy's of that category!</h4></div>
<div class="row text-center tag-row" id="tags"></div>
<div class="row text-center category-row">
<input type="" name="" id="category"><button class="btn btn-secondary" id="addTag">Add Category</button>
</div>
</div>
<div class="container">
<div id="photo"></div>
</div>
<script src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
<script type="text/javascript">
var tags = ["dog", "dolphin", "whale", "cat", "elephant", "otter"];
// Function for displaying movie data
function renderButtons() {
$("#tags").empty();
for (var i = 0; i < tags.length; i++) {
$("#tags").append('<button class="tag-buttons btn btn-primary">' + tags[i] + '</button>');
}
}
// Add tags function //
$(document).on('click', '#addTag', function(event) {
event.preventDefault();
var newTag = $("#category").val().trim();
tags.push(newTag);
$("#tags").append('<button class="tag-buttons btn btn-primary">' + newTag + '</button>');
});
// Tag button function //
$(document).on('click', '.tag-buttons', function(event) {
// Keeps page from reloading //
event.preventDefault();
var type = this.innerText;
console.log(this.innerText);
var queryURL = "http://api.giphy.com/v1/gifs/search?q=" + window.encodeURI(type) + "&limit=10&api_key=dc6zaTOxFJmzC";
$.ajax({
url: queryURL,
method: "GET"
}).done(function(response) {
for (var i = 0; i < response.data.length; i++) {
$("#photo").append('<img src="' + response.data[i].images.fixed_height_still.url + '" class="animate">');
$('.animate').on('click', function() {
$(this).remove().append('<img src="' + response.data[i].images.fixed_height.url + '" class="animate">');
console.log($(this));
});
}
});
$("#photo").empty();
});
renderButtons();
</script>
</body>
</html>
The difference between fixed_height and fixed_height_still will solve the problem. if you look closely the urls differ only by name_s.gif and name.gif.
So you can simply swap the two images to create a player. This will act like a play and stop. Not play and pause. But in a small gif I don't think pause really matter, stop and pause will look similar.
adding class name to the #photo
$("#photo").append('<img class="gif" src="' + response.data[i].images.fixed_height_still.url + '">');
event handler which will control play and stop
$('body').on('click', '.gif', function() {
var src = $(this).attr("src");
if($(this).hasClass('playing')){
//stop
$(this).attr('src', src.replace(/\.gif/i, "_s.gif"))
$(this).removeClass('playing');
} else {
//play
$(this).addClass('playing');
$(this).attr('src', src.replace(/\_s.gif/i, ".gif"))
}
});
jsfiddle demo
https://jsfiddle.net/karthick6891/L9t0t1r2/
you can use this jquery plugin http://rubentd.com/gifplayer/
<img class="gifplayer" src="media/banana.png" />
<script>
$('.gifplayer').gifplayer();
</script>
you can control like this
Use these methods to play and stop the player programatically
$('#banana').gifplayer('play');
$('#banana').gifplayer('stop');
youll find more details here https://github.com/rubentd/gifplayer

Element in jquery unable read css file

I've css style and jquery script at the same file. But my element in jquery is unable to read the css. Element that should take part are li,label, .selector, button. And also when I "Click Here" no alert come out.
Here is my jquery script:
$(document).ready(function(){
$.ajax({
//type: "POST",
url: "http://10.1.17.20:8040/services/getArticle",
success: function (data) {
var data2 = data.result.target;
btnTarget="<ul>";
for(var i=0; i<data2.length; i++){
btnTarget += "<li'><input id='"+data2[i].id+"' type='checkbox'>";
btnTarget += "<label for='"+data2[i].id+"'>"+data2[i].target_name+"</label></li>";
}
btnTarget += "</ul>";
btnTarget += "<button type='button' id='btnMenu'>Click Here</button>"
$(".selector").append(btnTarget);
},error: function (xhr, ajaxOptions, thrownError) {alert("ERROR:" + xhr.responseText+" - "+thrownError);}
});
});
$("document").on("click", "#btnMenu", function(){
alert("You Click");
});
var nbOptions = 8;
var angleStart = -360;
// jquery rotate animation
function rotate(li,d) {
$({d:angleStart}).animate({d:d}, {
step: function(now) {
$(li)
.css({ transform: 'rotate('+now+'deg)' })
.find('label')
.css({ transform: 'rotate('+(-now)+'deg)' });
}, duration: 0
});
}
// show / hide the options
function toggleOptions(s) {
$(s).toggleClass('open');
var li = $(s).find('li');
var deg = $(s).hasClass('half') ? 180/(li.length-1) : 360/li.length;
for(var i=0; i<li.length; i++) {
var d = $(s).hasClass('half') ? (i*deg)-90 : i*deg;
$(s).hasClass('open') ? rotate(li[i],d) : rotate(li[i],angleStart);
}
}
$(document).on('click','.selector button',function(e){
toggleOptions($(this).parent());
});
This is a part of html file.
<section class="content">
<!-- Your Page Content Here -->
<div class="row">
<!-- right column -->
<div class="col-md-12">
<!-- Horizontal Form -->
<div class="box box-info">
<!-- form start -->
<form class="form-horizontal">
<div class="box-body">
<div class="form-group">
<div class="selector">
</div><!-- /.selector -->
</div>
</div><!-- /.box-body -->
</form>
</div><!-- /.box -->
</div><!--/.col (right) -->
</div><!-- /.row -->
</section>
Here also i put some css style. This is only few. The css style is too long
.selector button:hover { background: #3071a9; }
.selector button:focus { outline: none; }
.selector ul {
position: absolute;
list-style: none;
padding: 0;
margin: 0;
top: -20px;
right: -20px;
bottom: -20px;
left: -20px;
}
.selector li {
position: absolute;
width: 0;
height: 100%;
margin: 0 50%;
-webkit-transform: rotate(-360deg);
transition: all 0.8s ease-in-out;
}
.selector li input { display: none; }
Thanks in advance.
When you run this:
$("#btnMenu").on("click",function(){
alert("You Click");
});
btnMenu does not yet exist, so it isn't able to bind the eventHandler. You could do use event delegation like this:
$("body").on("click", "#btnMenu", function(){
alert("You Click");
});
and it will work.
For the css, my first thought is that it has to do with this:
<li'>
See the stray single quote? Probably messing stuff up down the line. Also, a lot of your jquery is outside of $(document).ready(function(){ so it may be running too early.
Try with this (cleaned up some single quotes:
$(document).ready(function(){
$.ajax({
//type: "POST",
url: "http://10.1.17.20:8040/services/getArticle",
success: function (data) {
var data2 = data.result.target;
btnTarget="<ul>";
for(var i=0; i<data2.length; i++){
btnTarget += "<li><input id="+data2[i].id+" type='checkbox'>";
btnTarget += "<label for="+data2[i].id+">"+data2[i].target_name+"</label></li>";
}
btnTarget += "</ul>";
btnTarget += "<button type='button' id='btnMenu'>Click Here</button>"
$(".selector").append(btnTarget);
},error: function (xhr, ajaxOptions, thrownError) {
//alert("ERROR:" + xhr.responseText+" - "+thrownError);
}
});
});
Also, you should get in the habit of doing this in case elements you are adding listeners to don't yet exist in the DOM:
$(document).on("click",$("#btnMenu"),function(){
alert("You Click");
});
Instead of:
$("#btnMenu").on("click",function(){
alert("You Click");
});

Categories