Reputation: 3962
I want to be able to create a input field where you can enter CSS and have that input value and only that input value be applied to the page.
You can apply any amount of input values to the page and each time it will reset the previous.
Here is what i tried, and it works except for the part where i'm trying to reset the css so i've commented that line out (.remove).
$('input').on('change', function(){
//$('style')[1].remove();
var input = $('input').val();
var style = $('<style>span'+ input +'{background:yellow }</style>')
$('html > head').append(style);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input value=":nth-child(3)">
<span>1</span>
<span>2</span>
<span>3</span>
<span>4</span>
<span>5</span>
<span>6</span>
<span>7</span>
<span>8</span>
<span>9</span>
<span>10</span>
Upvotes: 1
Views: 177
Reputation: 3337
Try snippet below. I wrapped the span in a DIV in my sample snippet because the stackoverflow snippet editor has extra span in its content which adds more extra empty span elements before span 1.
working code for your example is simply:
$(function(){
$('input').on('keyup blur',function(){
$('span').css('background','none');
var input = $('input').val();
var elm = $('span' + input);
elm.css('background','yellow');
});
})
<span>1</span>
<span>2</span>
<span>3</span>
<span>4</span>
<span>5</span>
<span>6</span>
<span>7</span>
<span>8</span>
<span>9</span>
<span>10</span>
All i had to do to reset the css was to set background to none on initialisation. goodluck
$(function(){
$('input').on('keyup blur',function(){
$('.contain span').css('background','none');
var input = $('input').val();
var elm = $('.contain span' + input);
elm.css('background','yellow');
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input value=":nth-child(3)">
<div class="contain">
<span>1</span>
<span>2</span>
<span>3</span>
<span>4</span>
<span>5</span>
<span>6</span>
<span>7</span>
<span>8</span>
<span>9</span>
<span>10</span>
</div>
Upvotes: 1
Reputation: 11106
Give the style
an id:
$('input').on('change', function(){
var input = $('input').val();
$("#s1").remove();
var style = $('<style id="s1">span'+ input +'{background:yellow }</style>');
$('html > head').append(style);
})
fiddle here
Upvotes: 0