how to add submit function to js Onclick function [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
i am trying to trigger a url when click on a button, when click on the delete button it triggers the JS Alert but it is not passing the link, it removes the button instead. how can make it process the link once i confirm the alert?
js code
<script>
$(function() {
$('#demo').confirmOn('click', function() {
$(this).remove();
});
});
</script>
html
<a href="index.php?page=test:delete&item_id={item_id}" id="demo">
<input type="button" class="log_button" value="Delete"/>
ConfirmOn code..
(function($) {
var confirmOn = $.confirmOn = {};
confirmOn.providedOptions = {};
confirmOn.defaultSettings = {
questionText: 'Are you sure?',
classPrepend: 'confirmon',
textYes: 'Yes',
textNo: 'No'
};
confirmOn.overrideDefaultSettings = function(settings) {
confirmOn.defaultSettings = $.extend({}, confirmOn.defaultSettings, settings);
};
confirmOn.setOptions = function($element, options) {
options = $.extend({}, confirmOn.defaultSettings, options);
$element.data('confirmon', {
options: options
});
};
confirmOn.createOverlay = function($element) {
var classPrepend = $element.data('confirmon').options.classPrepend;
return $('<div/>').addClass(classPrepend + '-overlay').hide().appendTo('body');
};
confirmOn.showOverlay = function($element) {
var classPrepend = $element.data('confirmon').options.classPrepend;
$('.' + classPrepend + '-overlay').fadeIn();
};
confirmOn.deleteOverlay = function($element) {
var classPrepend = $element.data('confirmon').options.classPrepend;
$('.' + classPrepend + '-overlay').fadeOut(function(){
$(this).remove();
});
};
confirmOn.createBox = function($element) {
var classPrepend = $element.data('confirmon').options.classPrepend;
var questionText = $element.data('confirmon').options.questionText;
var textYes = $element.data('confirmon').options.textYes;
var textNo = $element.data('confirmon').options.textNo;
var $box = $('<div/>').addClass(classPrepend + '-box').hide().appendTo('body');
$('<p class="' + classPrepend + '-content"/>')
.html(questionText)
.appendTo($box);
$('<button class="' + classPrepend + '-button ' + classPrepend + '-button--yes"/>')
.html(textYes)
.appendTo($box);
$('<button class="' + classPrepend + '-button ' + classPrepend + '-button--no"/>')
.html(textNo)
.appendTo($box);
$('.' + classPrepend + '-button').on('keydown', function(e){
if (e.which === 9) { //Tab key
e.preventDefault();
$('.' + classPrepend + '-button').not(this).focus();
}
});
};
confirmOn.showBoxAndFocusNo = function($element) {
var classPrepend = $element.data('confirmon').options.classPrepend;
$('.' + classPrepend + '-box').fadeIn(function(){
$(this).children('button').eq(1).focus();
});
};
confirmOn.deleteBox = function($element) {
var classPrepend = $element.data('confirmon').options.classPrepend;
$('.' + classPrepend + '-box').fadeOut(function(){
$(this).remove();
});
};
$.confirmOn.handleEscKey = function($element) {
$(document).on('keydown.confirmon.close', function(e){
if (e.which === 27) { //Esc key
$.confirmOn.deleteOverlay($element);
$.confirmOn.deleteBox($element);
$(document).off('keydown.confirmon.close');
}
});
}
confirmOn.convertArguments = function(options, events, selector, data, handler) {
if (typeof options === 'object') {
$.each(options, function(key, val) {
if (typeof val === 'string') { //Options provided so shift all args to left
confirmOn.providedOptions = options;
options = events;
events = selector;
selector = data;
data = handler;
return false;
} else { //No options
confirmOn.providedOptions = {};
}
});
} else {
confirmOn.providedOptions = {};
}
if (selector == null && data == null && handler == null) {
//(events[S], handler)
selector = events;
events = options;
} else if (data == null && handler == null) {
//(events[S], selector, handler)
//(events[S], data, handler)
data = selector;
selector = events;
events = options;
} else {
handler = data;
data = selector;
selector = events;
events = options;
}
if (typeof events === 'object') {
//Implementation .on( events [, selector ] [, data ] )
return {
events: events,
selector: selector,
data: data
};
} else {
//Implementation .on( events [, selector ] [, data ], handler(eventObject) )
return {
events: events,
selector: selector,
data: data,
handler: handler
};
}
};
$.confirmOn.attachHandlers = function($element, handler, event) {
var classPrepend = $element.data('confirmon').options.classPrepend;
$('.' + classPrepend + '-box button').eq(0).on('click', function(){
$.confirmOn.deleteOverlay($element);
$.confirmOn.deleteBox($element);
handler.call($element.get(), event, true); //Call the handler function. the TRUE parameter indicates that the user pressed the YES button
});
$('.' + classPrepend + '-box button').eq(1).on('click', function(){
$.confirmOn.deleteOverlay($element);
$.confirmOn.deleteBox($element);
handler.call($element.get(), event, false); //Call the handler function. the FALSE parameter indicates that the user pressed the YES button
});
};
$.fn.confirmOn = function(options, events, selector, data, handler) {
var userHandler;
if (typeof events === 'function') {
userHandler = events;
events = confirmHandler;
} else if (typeof selector === 'function') {
userHandler = selector;
selector = confirmHandler;
} else if (typeof data === 'function') {
userHandler = data;
data = confirmHandler;
} else if (typeof handler === 'function') {
userHandler = handler;
handler = confirmHandler;
}
var $element = $(this);
var onArgs = $.confirmOn.convertArguments(options, events, selector, data, handler);
$.confirmOn.setOptions($element, $.confirmOn.providedOptions);
$element.on(onArgs.events, onArgs.selector, onArgs.data, onArgs.handler);
function confirmHandler(event) {
event.preventDefault();
$.confirmOn.createOverlay($element);
$.confirmOn.showOverlay($element);
$.confirmOn.createBox($element);
$.confirmOn.showBoxAndFocusNo($element);
$.confirmOn.handleEscKey($element);
$.confirmOn.attachHandlers($element, userHandler, event);
};
};
}(jQuery));

Use confirm():
Try this:
$("#demo").click(function() {
var confirm1 = confirm('Dialogue');
if (confirm1) {
$(this).remove();
return true;
} else {
return false;
}
});
UPDATE
$(function () {
$('#demo').confirmOn('click', function (e, confirmed) {
if (confirmed) { // Clicked yes
document.location.href= $(this).attr('href');
$(this).remove();
$('#msg_button_1').remove();
} else { // Clicked no
$('#msg_button_1').fadeIn();
}
});
});
JSFiddle Demo

Edited
<script>
$(function() {
$('.log_button').confirmOn('click', function(e, confirmed) {
if(confirmed){
//$('#demo').remove();
$('#demo').click();
}else{
alert("not go");
}
});
});
</script>
is this the thing that you actually want to do? click the button and then go to the link?

Related

How to prevent a click on an element just displayed

I have a "show link" that when clicked displays a hidden < li > containing other links.
These links happen to display at the exact co-ordinates of the "show link".
When "show Link" is clicked, its event is fired, but then the link below also is triggered.
How to I stop the newly shown links from being clicked when I click "show link"?
Edit:
I am providing the code, but it may complicate the issue. The setTapClickAction is to avoid the double click behaviour that you get using .on("touchstart click")
Inline script:
...
let $m = $('<a href="#"/>').text('Show Link');
$.setTapClickAction($m, function (el, e) {
$('li.location').fadeIn( 1000);
$(el).text("Show All").attr("href","https://example.com")
});
$('<p id="more-locations"/>').html($m).insertAfter(list);
...
main.js:
// function to set the tap or click action on an element.
// suggested usage:
// $.setTapClickAction('.subscription_show_button', function(){
// $modalElement.modal('show');
// });
$.setTapClickAction = function (selector, actionFunction){
if (typeof actionFunction !== 'function' ){
console.log('No Action Function given. Function tapClickButton');
return false;
}
let $obj;
if (typeof selector === 'string'){
$obj = $(selector);
} else if (selector instanceof $) {
$obj = selector;
} else {
console.log('No element for action: ' + selector);
return false;
}
let touchmoved;
$obj.on('click',function(e){
actionFunction($(this), e);
console.log("click fired by " + this);
}).on('touchend',function (e) {
if (touchmoved !== true) {
actionFunction($(this), e);
}
}).on('touchstart', function () {
$(this).off('click');
touchmoved = false;
console.log("touchstart fired by " + this);
}).on('touchmove', function () {
touchmoved = true;
});
};
edit2:
Here is a link to the production site. https://t.starstarmobile.com/5/SESSIONIDB10/quick2?phone=8887186545 click or tap the "find other centers near you"
So my answer to the problem was to use .preventDefault() on any links that did not have an href value. I also added namespaces so that the events could be modified multiple times.
// function to set the tap or click action on an element.
// suggested usage:
// $.setTapClickAction('.subscription_show_button', function(){
// $subscriptionModal.modal('show');
// });
$.setTapClickAction = function (selector, actionFunction) {
let $obj, touchmoved, hasHref;
let namespace = "";
if (typeof actionFunction !== 'function') {
console.log('No Action Function given. Function tapClickButton');
return false;
}
if (typeof selector === 'string') {
$obj = $(selector);
//set the name space
namespace = selector.charAt(0) !== '.' ? '.' + selector : selector;
// console.log("string selector", selector);
} else if (selector instanceof $) {
$obj = selector;
// console.log("jquery Instance", selector);
} else {
console.log('No element for action:', selector);
return false;
}
//look for valid href or exec e.preventDefault
let href = $obj.attr("href");
if (href !== '#' && href !== undefined) {
hasHref = true;
// console.log ("Href: " + href)
}
//remove previously set events
$obj.off('click' + namespace);
$obj.off('touchstart' + namespace);
$obj.off('touchend' + namespace);
$obj.off('touchmove' + namespace);
//set events
// console.log('namespace: '+ namespace);
$obj.on('click' + namespace, function (e) {
if (!hasHref) {
e.preventDefault();
}
actionFunction($(this), e);
// console.log("click fired by ", this);
}).on('touchend' + namespace, function (e) {
if (touchmoved !== true) {
actionFunction($(this), e);
}
}).on('touchstart' + namespace, function (e) {
if (!hasHref) {
e.preventDefault();
}
$(this).off('click' + namespace);
touchmoved = false;
// console.log("touchstart fired by:", this, e.currentTarget.getAttribute("href"));
}).on('touchmove' + namespace, function () {
touchmoved = true;
});
};

Setup jqueryui before element is rendered

In creating a table cells with very cool options I need to take two steps. First I create the table cell as a DOM object in javascript with all the 'normal' functionality, like is it a checkbox, a select, an input, a link, etc.
Then I need to put the table on the page to do the next step, which I consider advanced functionality like jqueryui's autocomplete and date select. It is awesome to have these drop downs for the user.
I do have this working, however, I do need to make two calls. The first to createTableCell, then I render, then I need to make another call to postRenderTableFunctions to get the autocomplete functionality working. So the question is, why the second call, what is it about jqueryui that will not work on the first call. You can see the commented section under input creation where I tried to get the autocomplete working.
function createTableCell(name, td_def)
{
var cell=document.createElement('td');
if(td_def['type'] == 'date')
{
var element = document.createElement('input');
element.name = name;
element.id = name;
cell.appendChild(element);
$('#' + element.id).datepicker(
{
dateFormat: 'yy-mm-dd',
onSelect: function ()
{
$(this).focus();
},
onClose: function (dateText, inst)
{
$(this).select();
}
});
}
else if(td_def['type'] == 'checkbox')
{
element = document.createElement('input');
element.type = 'checkbox';
element.name = name;
element.id = name;
/*if(this.tdo[r][td_def['db_field']]['data'] == 1)
{
element.checked = true;
}*/
cell.appendChild(element);
}
else if (td_def['type'] == 'select')
{
element = document.createElement('select');
element.name = name;
element.id = name;
var option = document.createElement('option');
option.value = 'NULL';
option.appendChild(document.createTextNode("Select..."));
element.appendChild(option);
for (var j in td_def['select_names'])
{
option = document.createElement('option');
option.value = td_def['select_values'][j];
option.appendChild(document.createTextNode(td_def['select_names'][j]));
element.appendChild(option);
}
cell.appendChild(element);
}
else if (td_def['type'] == 'tree_select')
{
element = document.createElement('select');
element.id = name;
element.name = name;
var option = document.createElement('option');
option.value = 'NULL';
option.appendChild(document.createTextNode("Select..."));
element.appendChild(option);
var level = 0;
//console.log(td_def['select_array']);
this.addNestedSelectOptions(element, td_def['select_array'], level);
if (typeof td_def['properties'] !== 'undefined')
{
for (var index in td_def['properties'])
{
eval('element.' + index + '= ' + td_def['properties'][index] + ';');
}
}
cell.appendChild(element);
}
else if (td_def['type'] == 'input')
{
element = document.createElement('input');
element.type = 'text';
element.id = name;
element.name = name;
cell.appendChild(element);
/*
if(typeof td_def['autoComplete'] != 'undefined')
{
console.log('attempting Autocomplete');
$( "#" + name ).autocomplete({
source: function( request, response )
{
$.ajax(
{
url: td_def['autoComplete']['url'],
type: 'GET',
async: true,
data:
{
ajax_request: td_def['autoComplete']['ajax_request'],
featureClass: "P",
style: "full",
maxRows: 12,
search_terms: request.term
},
success: function( data )
{
console.log(data);
parsed_autocomplete_data = parseJSONdata(data);
response( parsed_autocomplete_data);
}
});
},
search: function()
{
// custom minLength
var term = this.value;
//console.log(term);
if(typeof td_def['minLength'] != 'undefined')
{
var minL = td_def['minLength'];
}
else
{
var minL = 1;
}
if ( term.length < minL )
{
return false;
}
},
focus: function()
{
// prevent value inserted on focus
return false;
},
open: function(event, ui)
{
var dialog = $(this).closest('.ui-dialog');
if(dialog.length > 0){
$('.ui-autocomplete.ui-front').zIndex(dialog.zIndex()+1);
}
},
select: function( event, ui )
{
selected_autocomplete_index = $.inArray(ui.item.value, parsed_autocomplete_data);
}
});
}
*/
}
else if (td_def['type'] == 'textarea')
{
element = document.createElement('TEXTAREA');
element.id = name;
element.name = name;
cell.appendChild(element);
}
else if (td_def['type'] == 'td')
{
cell.innerHTML = 'TBD';
cell.name = name;
cell.id = name;
}
else
{
alert(td_def['type'] + ' have not coded that.....');
}
return cell;
function addNestedSelectOptions(element, category_array, level)
{
for (var key in category_array)
{
option = document.createElement('option');
option.value = key;
name = category_array[key]['name'];
for(i=0;i<level;i++)
{
name = "\u00A0" + name;
name = "\u00A0" + name;
}
option.appendChild(document.createTextNode(name));
element.appendChild(option);
if(!$.isEmptyObject(category_array[key]['children']))
{
addNestedSelectOptions(element, category_array[key]['children'], level+1);
}
}
}
}
//this function needs to be called separately.
function postRenderTableFunctions(table_div_id, table_def)
{
//extra jquery functionality -- needs to go after stuff is rendered
for(var i=0;i<table_def.length;i++)
{
if(typeof table_def[i]['autoComplete'] != 'undefined')
{
var id = table_div_id + '_' + table_def[i]['db_field'];
console.log(id);
//is the auto complete open?
/*$("#" + id ).bind('autocompleteopen', function(event, ui)
{
$(this).data('is_open',true);
});
$("#" + id ).bind('autocompleteclose', function(event, ui)
{
$(this).data('is_open',false);
});*/
/*$( "#" + id ).bind( "keydown", function( event )
{
//what is this for ?
if ( event.keyCode === $.ui.keyCode.TAB && $(this).data('is_open') )
{
event.preventDefault();
}
if ( event.keyCode === $.ui.keyCode.ENTER && !$(this).data('is_open'))
{
//do what?
}
});*/
var i2 = i;
var me = table_def;
$( "#" + id ).autocomplete({
source: function( request, response )
{
$.ajax(
{
url: me[i2]['autoComplete']['url'],
type: 'GET',
async: true,
data:
{
ajax_request: me[i2]['autoComplete']['ajax_request'],
featureClass: "P",
style: "full",
maxRows: 12,
search_terms: request.term
},
success: function( data )
{
console.log(data);
parsed_autocomplete_data = parseJSONdata(data);
response( parsed_autocomplete_data);
}
});
},
search: function()
{
// custom minLength
var term = this.value;
//console.log(term);
if(typeof table_def[i2]['minLength'] != 'undefined')
{
var minL = table_def[i2]['minLength'];
}
else
{
var minL = 1;
}
if ( term.length < minL )
{
return false;
}
},
focus: function()
{
// prevent value inserted on focus
return false;
},
open: function(event, ui)
{
var dialog = $(this).closest('.ui-dialog');
if(dialog.length > 0){
$('.ui-autocomplete.ui-front').zIndex(dialog.zIndex()+1);
}
},
select: function( event, ui )
{
selected_autocomplete_index = $.inArray(ui.item.value, parsed_autocomplete_data);
}
});
}
}
}
My original comment to your question -
I suspect i may work if you replace
$( "#" + name ).autocomplete({
with
$(element).autocomplete({
though I don't currently have means to test it.
My response -
Basically using $("#name") looks for an element with the ID name in the DOM. When you are running your code element has not been added to the DOM yet so the autocomplete cannot be attached to to your element.
Surrounding element with $() converts it to a jQuery variable which you can attach the autocomplete to before it is added to the DOM.

Nothing happend on click - jQuery

I have this code:
jQuery.fn.extend({
SelectBox: function(options) {
return this.each(function() {
new jQuery.SelectBox(this, options);
});
}
});
jQuery.SelectBox = function(selectobj, options) {
var opt = options || {};
opt.inputClass = opt.inputClass || "inputClass";
opt.containerClass = opt.containerClass || "containerClass";
var inFocus = false;
var $select = $(selectobj);
var $container = setupContainer(opt);
var $input = setupInput(opt);
$select.hide();
hideMe();
$input
.click(function(){
if (!inFocus) {
showMe();
} else {
hideMe();
}
})
.keydown(function(event) {
switch(event.keyCode) {
case 27:
hideMe();
break;
}
})
.blur(function() {
if ($container.not(':visible')) {
hideMe();
}
});
function showMe() {
$container.show();
inFocus = true;
}
function hideMe() {
$container.hide();
inFocus = false;
}
function setupContainer(options){
$container = $("." + options.containerClass);
$input = $("." + options.inputClass);
var first = false;
var li = "";
$select.find('option').each(function(){
if($(this).is(':selected')){
$input.find('span').text($(this).text());
first = true;
}
//var $li = $container.find('ul').append('<li>' + $(this).text() + '</li>');
var li = document.createElement('li');
li.innerHTML = $(this).text();
$container.find('ul').append(li);
$(li).click(function(event){
$(li).remove();
});
});
return $container;
}
function setupInput(options){
$input = $("." + options.inputClass);
$input.attr('tabindex', '0');
return $input;
}
};
In this code, the "select" i choose hidden, and replaced by a list.
Now, i want click on some "li", and "li" removed.
But, i click on the "li" i have created, and nothing happened.
Why? how can i remove or do anything else when i click on the "li"?
There is no need to add event to each individual element. Use event delegation.
$(document).ready(function() {
$(commonParentSelector).on('click', 'li', function() {
// ^^^^^^^^^^^^^^^^^^^^
$(this).remove();
});
});
Update commonParentSelector according to your needs and it should work.
Docs: https://api.jquery.com/on
use var $li = $("<li>").text($(this).text()).appendTo($container.find('ul'));

click event not completely working, using Knockout.js binding and viewmodel

hi this is my code snippet:
self.arrow = function () {
alert("button clicked");
var active_el = $(this);
$('.movie-listing-header').each(function () {
if ($(this).get(0) === active_el.parent().get(0)) {
if ($(this).hasClass('active')) {
$(this).siblings('.showtimes').hide();
} else {
$(this).siblings('.showtimes').show();
}
$(this).toggleClass('active');
} else {
$(this).removeClass('active');
$(this).siblings('.showtimes').hide();
}
});
}
it is part of my viewmodel, and the alert("button clicked") works, but the rest of the code does not ... Here is the button click code:
<a class="icon arrow" data-bind="click: $parent.arrow"></a>
my question is HOW do I get the code after the alert to function.
this is the entire js, containing the the View Model
function TheatreViewModel(theatre) {
var self = this,
initialData = theatre || Regal.userPrimaryTheatre || {},
theatreServiceParams = {
tmsId: initialData.TmsId,
date: initialData.selectedDate || new Date()
};
self.TheatreName = initialData.TheatreName || '';
self.PhoneNumber = initialData.PhoneNumber || '';
self.selectedTheatreTms = initialData.TmsId;
self.theatre = ko.observable();
self.isLoading = ko.observable(false);
self.selectedDate = ko.observable(initialData.selectedDate || new Date());
self.filterFormats = [];
self.selectedFormat = ko.observable(Regal.allFormatsFilterItem);
self.filterFormats.push(Regal.allFormatsFilterItem);
if (Regal.movieFormats) {
var filtered = _.where(Regal.movieFormats, {
Filterable: true
});
_.forEach(filtered, function(f) {
f.enabled = ko.observable(false);
self.filterFormats.push(f);
});
}
self.addressText = ko.computed(function() {
var theat = ko.unwrap(self.theatre);
var addie;
if (!theat || theat && !theat.Address1) {
addie = initialData;
} else {
addie = theat;
}
return addie.Address1 + ', ' + addie.City + ' ' + addie.State + ' ' + addie.PostalCode;
});
self.mapEmbedUrl = ko.computed(function() {
var a = self.addressText();
return 'http://maps.google.com/maps?q=' + encodeURI(a);
});
self.movies = ko.computed(function() {
var thea = self.theatre(),
mov = ko.unwrap((thea || {}).Movies),
format = self.selectedFormat();
if (format && format !== Regal.allFormatsFilterItem) {
return _.filter(mov, function(m) {
return _.contains(_.pluck(m.formats(), 'Id'), format.Id);
});
}
return mov;
});
self.getPerformances = function() {
self.isLoading(true);
Regal.loadTheatre(self.selectedDate(), self.selectedTheatreTms,
function(data) {
self.isLoading(false);
if (data) {
var allFmts = _.uniq(_.flatten(_.map(ko.unwrap(data.Movies), function(mov) {
return mov.formats();
})));
_.forEach(allFmts, function(fmt) {
var filt = _.findWhere(self.filterFormats, {
Id: fmt.Id
});
if (filt) {
filt.enabled(true);
}
});
self.theatre(data);
}
});
};
self.changeFormat = function(format) {
console.log(format);
self.selectedFormat(format);
self.movies();
};
self.selectedDate.subscribe(function(newVal) {
self.getPerformances();
});
self.getPerformances();
self.arrow = function () {
alert("button clicked");
var active_el = $(this);
$('.movie-listing-header').each(function () {
if ($(this).get(0) === active_el.parent().get(0)) {
if ($(this).hasClass('active')) {
$(this).siblings('.showtimes').hide();
} else {
$(this).siblings('.showtimes').show();
}
$(this).toggleClass('active');
} else {
$(this).removeClass('active');
$(this).siblings('.showtimes').hide();
}
});
}
}
I have a feeling that var active_el = $(this) is not what you're expecting. I'm not running the code but I believe that this will be self in this context. However, I'd like to recommend a more fundamental MVVM change. Rather than including all this jQuery code for updating the UI, I would recommend setting properties on your view model instead. Here's a simplified example:
HTML
<section data-bind="foreach: movies">
<article>
<div data-bind="if: displayShowtimes">
<!-- ... show times UI -->
</div>
</article>
</section>
JavaScript
self.arrow = function (movie) {
movie.isActive(!movie.isActive());
}
This will make your JavaScript much less brittle to changes in the HTML.

How to select all images in the page?

I have this jQuery-script that gives any image or object with tag data-retina="true" a retina-resolution-image or background-image.
But how do I remove the last part from the script so that this function will apply on every image, not just the one with the data-retina tag?
(function($) {
"use strict";
var retinaReplace = function(element, options) {
this.options = options;
var $el = $(element);
var is_image = $el.is('img');
var normal_url = is_image ? $el.attr('src') : $el.backgroundImageUrl();
var retina_url = this.options.generateUrl($el, normal_url);
$('<img/>').attr('src', retina_url).load(function() {
if (is_image) {
$el.attr('src', $(this).attr('src'));
} else {
$el.backgroundImageUrl($(this).attr('src'));
$el.backgroundSize($(this)[0].width, $(this)[0].height);
}
$el.attr('data-retina', 'complete');
});
}
retinaReplace.prototype = {
constructor: retinaReplace
}
$.fn.retinaReplace = function(option) {
if (getDevicePixelRatio() <= 1) { return this; }
return this.each(function() {
var $this = $(this);
var data = $this.data('retinaReplace');
var options = $.extend({}, $.fn.retinaReplace.defaults, $this.data(), typeof option == 'object' && option);
if (!data) { $this.data('retinaReplace', (data = new retinaReplace(this, options))); }
if (typeof option == 'string') { data[option](); }
});
}
$.fn.retinaReplace.defaults = {
suffix: '-x2',
generateUrl: function(element, url) {
var dot_index = url.lastIndexOf('.');
var extension = url.substr(dot_index + 1);
var file = url.substr(0, dot_index);
return file + this.suffix + '.' + extension;
}
}
$.fn.retinaReplace.Constructor = retinaReplace;
var getDevicePixelRatio = function() {
if (window.devicePixelRatio === undefined) { return 1; }
return window.devicePixelRatio;
}
$.fn.backgroundImageUrl = function(url) {
return url ? this.each(function () {
$(this).css("background-image", 'url("' + url + '")')
}) : $(this).css("background-image").replace(/url\(|\)|"|'/g, "");
}
$.fn.backgroundSize = function(retinaWidth, retinaHeight) {
var sizeValue = Math.floor(retinaWidth/2) + 'px ' + Math.floor(retinaHeight/2) + 'px';
$(this).css("background-size", sizeValue);
$(this).css("-webkit-background-size", sizeValue);
}
$(function(){
$("[data-retina='true']").retinaReplace();
});
})(window.jQuery);
how do I remove the last part from the script so that this function will apply on every image, not just the once with the data-retina-tag?
Change:
$(function(){
$("[data-retina='true']").retinaReplace();
});
To:
$(function(){
$("img").retinaReplace();
});

Categories