Skip to content

Instantly share code, notes, and snippets.

@rich-97
Last active June 10, 2021 14:21
Show Gist options
  • Save rich-97/bb5a7a3939e3283e6858d7b0f10c6334 to your computer and use it in GitHub Desktop.
Save rich-97/bb5a7a3939e3283e6858d7b0f10c6334 to your computer and use it in GitHub Desktop.
Example of pattern design oriented object in JavaScript.
$(document).ready(function () {
var $btn = $('.btn');
var $image = $('#img');
function Filter (config) {
this.target = config.target;
this.image = config.image;
this.filters = config.filters;
this.support = config.support === undefined ? true : config.support;
this.init = function () {
this.setFilter();
};
this.getFilter = function (type, amount) {
if (type === 'blur') {
return `${type}(${amount}px)`;
} else if (type === 'hue-rotate') {
return `${type}(${amount}deg)`;
} else {
return `${type}(${amount}%)`;
}
};
this.setCss = function (filter) {
if (this.support) {
this.image
.css('filter', filter)
.css('oFilter', filter)
.css('msFilter', filter)
.css('mozFilter', filter)
.css('webkitFilter', filter);
} else {
this.image.css('filter', filter);
}
};
this.setFilter = function () {
var count = 0;
var $this = this;
this.target.click(function () {
var type = $(this).text();
// A litle bit normalization.
type = type.toLowerCase();
type = type.replace(/\W/, '-');
if (type === 'reset') {
$this.setCss('initial');
count = 0;
} else if (type === 'hue-rotate') {
var amount = $this.filters.hueRotate;
count -= amount;
$this.setCss($this.getFilter(type, count));
} else {
var amount = $this.filters[type];
count += amount;
$this.setCss($this.getFilter(type, count));
}
});
}
}
var filter = new Filter({
target: $btn,
image: $image,
filters: {
blur: 0.1,
brightness: 5,
hueRotate: 10,
invert: 5,
sepia: 5,
}
});
filter.init();
});
<!DOCTYPE html>
<html>
<head>
<title>Pattern</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="filter.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-7">
<button class="btn">Reset</button>
<button class="btn">Blur</button>
<button class="btn">Brightness</button>
<button class="btn">Hue Rotate</button>
<button class="btn">Invert</button>
<button class="btn">Sepia</button>
</div>
</div>
</div>
<!-- Your beautiful image here. -->
<img src="image.png" id="img" width="300px" height="300px">
</body>
</html>
@CharlyJazz
Copy link

CharlyJazz commented Jan 16, 2017

Beautiful implement

@rich-97
Copy link
Author

rich-97 commented Jan 16, 2017

A small error in filter.js line: 9, should be if config.support is undefined then be true if not then be config.support.

@rich-97
Copy link
Author

rich-97 commented Jan 16, 2017

I will fix it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment